# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - ShowCSV

    This macro is used to show csv data as wiki table

    default extension is .csv
    you can change that with the args parameter

    First element of each column in csv table is used as column description

    (I have used the wiki parsers syntax, because then its quite easy to change that
     routine to add the csv content to the page as wiki content
     but its not clear to me if this is wanted)

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

Dependencies = ['time'] # do not cache

import os, codecs, csv
from MoinMoin import config, wikiutil
from MoinMoin.action import AttachFile
from MoinMoin.parser.text_moin_wiki import Parser

def utf_8_encoder(unicode_csv_data):
    for line in unicode_csv_data:
        yield line.encode('utf-8')

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

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

    pagename = formatter.page.page_name
    files = AttachFile._get_files(request, pagename)
    attach_dir = AttachFile.getAttachDir(request, pagename)

    for file in files:
        if file.lower().endswith(extension.lower()):
            file_id = codecs.open(os.path.join(attach_dir, file), 'rb', config.charset)
            reader = csv.reader(utf_8_encoder(file_id))
            index = 0
            result = ""
            for row in reader:
                if index == 0:
                    result += "|| '''"
                    result += "''' || '''".join(row)
                    result += "''' ||\n"
                else:
                    result += '|| '
                    result += '|| '.join(row)
                    result += ' ||\n'
                index += 1

            result += ' . \n'
            result = wikiutil.url_unquote(result)
            result += '[[attachment:%s]]' % file

            result = wikiutil.escape(result)
            p = Parser(result, request)
            p.format(request.formatter)

    return ""
