# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - Show Ames

    This macro is used to show correct data submission of ames files
    using a table showing some info of the file.

    comment: developed in 1.7, not ported to the macro parser yet, because
             compatibility to 1.5.8 / 1.6 is wanted.

    dependency: needs the nappy package from
                http://home.badc.rl.ac.uk/astephens/software/nappy

    @copyright: 2007 MoinMoin:ReimarBauer
    @license: GNU GPL, see COPYING for details.
"""

Dependencies = ['time'] # do not cache

import nappy, os
from MoinMoin import wikiutil
from MoinMoin.action import AttachFile
from MoinMoin.util.dataset import TupleDataset, Column
from MoinMoin.widget.browser import DataBrowserWidget


def execute(macro, args):
    request = macro.request
    formatter = macro.formatter
    _ = request.getText

    if args is None:
        extension = '.nas'
    else:
        extension = args

    COLUMNS = 1

    # initialize colums of output table
    data = TupleDataset()
    data.columns = []
    for dummy in range(COLUMNS):
        data.columns.extend([
            Column('file', label='file'),
            Column('date', label='date'),
            Column('short name', label='short name', align='center'),
            Column('unit', label='unit', align='center'),
            Column('first - last data val', label='first - last data val', align='center'),
            Column('', label='')
        ])
    # last column should be hidden    
    data.columns[-1].hidden = 1
    pagename = formatter.page.page_name
    files = AttachFile._get_files(request, pagename)
    attach_dir = AttachFile.getAttachDir(request, pagename)
    for file in files:
        result = []
        tmp_date = []
        tmp_short_name = []
        tmp_units = []
        tmp_first_last_data = []
        if file.lower().endswith(extension.lower()):
            # trying to open the ames file
            try:
                myfile = nappy.openNAFile(os.path.join(attach_dir, file))
            except:
                # Iam not sure if someone other as a python programmer
                # helps reading the traceback to find the failure 
                # in the file 
                result.append("<p>%s<br>%s</p>" % (wikiutil.escape(file), "ames file header is not correct"))
                for i in range(5): result.append('ERR')
                data.addRow(tuple(result))
                continue

            # trying to read the data of the ames file
            try:
                myfile.readData()
            except:
                result.append("<p>%s<br>%s</p>" % (wikiutil.escape(file), "is not of proper format"))
                for i in range(5): result.append('ERR')
                data.addRow(tuple(result))
                continue

            url = AttachFile.getAttachUrl(pagename, file, request, escaped=1)
            link = "%s%s%s" % (formatter.url(1, url),
                               formatter.text(file),
                               formatter.url(0))

            result.append(link)
            # getting the dict of ames file
            myfile.getNADict()
            # read the date key
            y, m, d = myfile.naDict["DATE"]
            tmp_date.append("%d-%d-%d" % (y, m, d))
            # get the independent var
            independent_var = myfile.getIndependentVariables()
            tmp_short_name.append(independent_var[0][0])
            if independent_var[0][1]:
                tmp_units.append(independent_var[0][1])
            else:
                tmp_units.append('')
            # get start and end value of independent parameter    
            start = myfile.naDict["X"][0]
            endof = myfile.naDict["X"][-1]
            tmp_first_last_data.append("%d - %d" % (start, endof))
            # get the dependent var's    
            dependent_var = myfile.getVariables()
            n_dependent = len(dependent_var)
            i = 0
            while i < n_dependent:
                tmp_short_name.append(dependent_var[i][0])
                tmp_units.append(dependent_var[i][1])
                # get start and end value of dependent parameters
                start = myfile.naDict["V"][i][0]
                endof = myfile.naDict["V"][i][-1]
                tmp_first_last_data.append("%d - %d" % (start, endof))
                i += 1
            # fill the table    
            result.append(formatter.linebreak(0).join(tmp_date))
            result.append(formatter.linebreak(0).join(tmp_short_name))
            result.append(formatter.linebreak(0).join(tmp_units))
            result.append(formatter.linebreak(0).join(tmp_first_last_data))
            data.addRow(tuple(result))
    if not data:
        return '<p>extension: %s: %s</p>' % (extension, _("No attachments stored for %(pagename)s") % {'pagename': wikiutil.escape(pagename)})
    browser = DataBrowserWidget(request)
    browser.setData(data)
    return browser.toHTML()

