#!/usr/bin/python
# -*- coding: utf-8  -*-
"""
This bot regenerates the page VEIDs

The following parameters are supported:

    -debug         If given, doesn't do any real changes, but only shows
                   what would have been changed.

"""
__version__ = '$Id: basic.py 4946 2008-01-29 14:58:25Z wikipedian $'
import wikipedia
import pagegenerators, catlib


class VEIDBot:
    # Edit summary message that should be used.
    # NOTE: Put a good description here, and add translations, if possible!
    msg = {
        'en': u'Robot: regenerated list.',
    }

    def __init__(self, generator, debug):
        """
        Constructor. Parameters:
            * generator - The page generator that determines on which pages
                          to work on.
            * debug     - If True, doesn't do any real changes, but only shows
                          what would have been changed.
        """
        self.generator = generator
        self.debug = debug
        self.veidlist = dict()
	self.companies = {10: 'IniTech', 20: 'ACME Corp.'} # FIXME: company-config file

    def run(self):
        # Set the edit summary message
        wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), self.msg))
        for page in self.generator:
            self.treat(page)

        overviewPage = wikipedia.Page(wikipedia.getSite(), u"VEIDs")

        text = "<!-- Note: automatically generated by robot-generate_openvz_velist.py. -->\n"
        text += "[VEID Naming Conventions]\n\n"
        text += "=== Legacy IDs ===\n"
        keys = self.veidlist.keys()
        keys.sort()
        lastid = ""
        for id in keys:
          pagename = self.veidlist[id]
          id = str(id)
          companyid = id[0:2]
          if (not lastid.startswith(companyid)) and len(id) > 4:
            text += "=== " + companyid + " - " + self.companies[int(companyid)] + " ===\n"
          text += "* [[" + pagename + "|'''" + id + "''']]''':''' [[" + pagename + "]]\n"
          if len(id) > 4: lastid = id
        text += "[[Category:VE]]"
        # only save if something was changed
        if text == overviewPage.get(): return

        # Show the title of the page we're working on.
        # Highlight the title in purple.
        wikipedia.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<" % overviewPage.title())
        # show what was changed
        wikipedia.showDiff(overviewPage.get(), text)
        choice = 'y'
        if self.debug: choice = wikipedia.inputChoice(u'Do you want to accept these changes?', ['Yes', 'No'], ['y', 'N'], 'N')
        if choice == 'y':
          try:
              # Save the page
              overviewPage.put(text)
          except wikipedia.LockedPage:
              wikipedia.output(u"Page %s is locked; skipping." % overviewPage.aslink())
          except wikipedia.EditConflict:
              wikipedia.output(u'Skipping %s because of edit conflict' % (overviewPage.title()))
          except wikipedia.SpamfilterError, error:
              wikipedia.output(u'Cannot change %s because of spam blacklist entry %s' % (overviewPage.title(), error.url))


    def treat(self, page):
        """
        Loads the given page, does some changes, and saves it.
        """
        try:
            # Load the page
            text = page.get()
        except wikipedia.NoPage:
            wikipedia.output(u"Page %s does not exist; skipping." % page.aslink())
            return
        except wikipedia.IsRedirectPage:
            wikipedia.output(u"Page %s is a redirect; skipping." % page.aslink())
            return

        # save veid into list
        for line in text.split("\n"):
          if not line.startswith("|VEID"): continue
          (junk, veid) = line.split("=")
	  #print "%s: %s" % (page.urlname(), repr(veid))
          self.veidlist[int(veid)] = page.urlname()

def main():
    # The generator gives the pages that should be worked upon.
    gen = None
    # If debug is True, doesn't do any real changes, but only show
    # what would have been changed.
    debug = False
    wantHelp = False

    cat = catlib.Category(wikipedia.getSite(), 'Category:%s' % 'VE')
    gen = pagegenerators.CategorizedPageGenerator(cat, start = None, recurse = False)

    # Parse command line arguments
    for arg in wikipedia.handleArgs():
        if arg.startswith("-debug"):
            debug = True
        else:
            print arg, "yielding wanthelp"
            wantHelp = True

    if not wantHelp:
        # The preloading generator is responsible for downloading multiple
        # pages from the wiki simultaneously.
        gen = pagegenerators.PreloadingGenerator(gen)
        bot = VEIDBot(gen, debug)
        bot.run()
    else:
        wikipedia.showHelp()

if __name__ == "__main__":
    try:
        main()
    finally:
        wikipedia.stopme()
