#!/usr/bin/env python

# (C) Legoktm, 2012 under the MIT License
"""
Code state: alpha
Goal: A comprehensive helper script for User:Legobot
Built on top of the pywikibot framework
Current Requirements:
    Configuration page set up at 'User:USERNAME/Configuration'
    pywikibot-rewrite framework installed
Currently supports:
    An on-wiki configuration subpage.
    
Usage:
import pywikibot
import robot
class TaskRobot(robot.Robot):
    def __init__(self):
       robot.Robot.__init__(self, task=1)
    def run(self):
        page = pywikibot.Page(self.site, 'Wikipedia:Sandbox')
        text = 'This is a test'
        msg = 'BOT: Edit summary'
        self.edit(page, text, msg)
if __name__ == "__main__":
    bot = TaskRobot()
    bot.run()

"""
from __future__ import unicode_literals
import sys
import re
import time
import pywikibot

CONFIGURATION_PAGE = 'User:%s/Configuration'
CHECK_CONFIG_PAGE_EVERY = 10 #edits

class Robot:
    
    def __init__(self, task):
        self.site = pywikibot.getSite()
        self.trial = False
        self.trial_counter = 0
        self.trial_max = 0
        self.summary = None
        self.username = self.site.username()
        self.CONFIGURATION_PAGE = CONFIGURATION_PAGE % self.username
        self.task = task
        self.site = pywikibot.getSite()
        self.loggingEnabled = False
        self.counter = 0
        self.CHECK_CONFIG_PAGE_EVERY = CHECK_CONFIG_PAGE_EVERY
        self.args = pywikibot.handleArgs()
    def setAction(self, text):
        self.summary = text
    
    def startLogging(self, logPage):
        self.loggingEnabled = True
        self.logPage = logPage
        self.logText = ''
    
    def pushLog(self, overwrite=False):
        if (not overwrite) and self.logPage.exists():
            old = self.logPage.get()
            self.logText = old + self.logText
        self.logPage.put(self.logText, 'BOT: Updating log')
        self.loggingEnabled = False
        self.logText = ''
        
    def output(self, text,debug=False):
        if self.loggingEnabled and not debug:
            self.logText += text
            if not text.endswith('\n'):
                self.logText += '\n'
        pywikibot.output(text)
    
            
        
    def edit(self, page, text, summary=False, async=False, force = False, minorEdit=False):
        if not force:
            if self.counter >= self.CHECK_CONFIG_PAGE_EVERY:
                if not self.isEnabled():
                    self.output('Run-page is disabled. Quitting.')
                    self.quit(1)
                else:
                    self.counter = 0
            else:
                self.counter += 1
        if not summary:
            summary = self.summary
        if async:
            page.put_async(text, summary, minorEdit=minorEdit)
        else:
            page.put(text, summary, minorEdit=minorEdit)
        if self.trial:
            self.trial_action()
        
    def trial_action(self):
        self.trial_counter += 1
        if self.trial_counter >= self.trial_max:
            print 'Finished trial, quitting now.'
            self.quit()
    
    def start_trial(self, count):
        self.trial = True
        self.trial_max = count
    
    def isEnabled(self):
        if self.task == 0: #override for non-filed tasks
            self.enabled = True
            return self.enabled
        page = pywikibot.Page(self.site, self.CONFIGURATION_PAGE)
        try:
            config = page.get()
        except pywikibot.exceptions.NoPage:
            self.enabled = False
            return self.enabled
        config = config.lower()
        if 'enable: all' in config: #be careful...
            self.enabled = True
            return self.enabled
        search = re.search('%s: (.*?)\nenable(|d): (true|.*?)\n' % self.task, config)
        if not search:
            self.enabled = False
        else:
            self.enabled = (search.group(3).lower() == 'true')
        return self.enabled
    
    def quit(self, status=0):
        #something fancy to go here later
        sys.exit(status)
    

@@ -797,16 +797,26 @@
 ort sys%0A
+import os%0A
 import r
@@ -927,16 +927,78 @@
 0 #edits
+%0ATS_USERNAME = 'legoktm'%0ALOG_PATH = '/home/%25s/public_html/%25s/'
 %0A%0Aclass 
@@ -1666,32 +1666,62 @@
 gEnabled = True%0A
+        self.localLog = False%0A
         self.log
@@ -1769,48 +1769,722 @@
     
-%0A    def pushLog(self, overwrite=False):
+    self.filled_path = LOG_PATH %25 (TS_USERNAME, self.username.lower())%0A        if os.path.isdir(self.filled_path):%0A            self.localLog = True%0A            self.logFile = self.filled_path + '%25s.txt' %25 str(self.task)%0A    %0A    def pushLog(self, overwrite=False):%0A        #first do all local logging, then try on-wiki%0A        if self.localLog:%0A            if not overwrite and os.path.isfile(self.logFile):%0A                f = open(self.logFile, 'r')%0A                old = f.read()%0A                logText = old + self.logText%0A                f.close()%0A            else:%0A                logText = self.logText%0A            f = open(self.logFile, 'w')%0A            f.write(logText)%0A            f.close()%0A            
 %0A   
@@ -2575,37 +2575,32 @@
 t()%0A            
-self.
 logText = old + 
@@ -2604,32 +2604,81 @@
  + self.logText%0A
+        else:%0A            logText = self.logText%0A
         self.log
@@ -4744,24 +4744,16 @@
 group(3)
-.lower()
  == 'tru

enable local logging for ts-users in the ~/public_html directory