# -*- coding: iso-8859-1 -*-
"""
MoinMoin - creates a dict page from an existing table

@copyright: 2009 MoinMoin:ReimarBauer
@license: GNU GPL, see COPYING for details.
"""
from MoinMoin import user, wikiutil
from MoinMoin.Page import Page
from MoinMoin.PageEditor import PageEditor
from MoinMoin.script import MoinScript

class PluginScript(MoinScript):
    """\
Purpose:
========
This tool allows you to create subpages having definition lists from a given table
in wiki markup. The first column entry is used for the subpage name while the first
line is used to get the keys.


Detailed Instructions:
======================
General syntax: moin [options] account create [create-options]

[options] usually should be:
    --config-dir=/path/to/my/cfg/ --wiki-url=wiki.example.org/

1. Use, the --file argument could be added to the above examples,
causing the script to respect ACLs.
1. Use a base --base_page argument for the page name
"""

    def __init__(self, argv, def_values):
        MoinScript.__init__(self, argv, def_values)

        self.parser.add_option(
            "-u", "--user", dest="homepage_creater",
            help="User as whom the homepage creation operation will be performed as. "
            )

        self.parser.add_option(
            "-b", "--base_page", dest="base_pagename",
            help="the base page of the subpages "
            )

        self.parser.add_option(
            "-f", "--file", dest="input_file",
            help="filename to proceed on"
            )

    def mainloop(self):
        # we don't expect non-option arguments
        self.init_request()
        request = self.request
        # Check for user
                # Check for user
        if self.options.homepage_creater:
            request.user = user.User(request, name=self.options.homepage_creater)

        filename = self.options.input_file
        base_page_name = self.options.base_pagename or u'Example'

        if not filename:
            print "Please provide the filename -f"
            return
        raw = open(filename, 'r').readlines()

        keys = (raw[0]).split('||')[1:-1]
        for line in raw[1:]:
            text = []
            if line.startswith('||'):
                row = line.split('||')[1:-1]
                idx = 0
                for key in keys:
                    text.append(' %s:: %s' % (key.strip(), (row[idx]).strip()))
                    idx += 1
                text = '\n'.join(text)

                pagename = '%s/%s' % (base_page_name, (row[0]).strip())
                print pagename
                page = PageEditor(request, pagename)
                if not request.user.disabled and not Page(request, pagename).exists():
                    try:
                        page._write_file(text, action='SAVE')
                        print "INFO page for %s created." % pagename
                    except page.Unchanged:
                            print "You did not change the page content, not saved!"
                else:
                    print "INFO page for %s already exists." % pagename
