print "Loading mod: scheduler v2016-01-09"
from debug_utils import LOG_NOTE
import ResMgr, os, json, codecs, re, time, datetime, BigWorld
from gui.app_loader import g_appLoader
from gui.app_loader.settings import GUI_GLOBAL_SPACE_ID as _SPACE_ID
from gui import SystemMessages
from messenger.proto.events import g_messengerEvents
from messenger.m_constants import SCH_CLIENT_MSG_TYPE

#from gui.DialogsInterface import showDialog
#from gui.Scaleform.daapi.view.dialogs import I18nInfoDialogMeta

config = {}
d = False
schedule = {}

def MYLOGLIVE(message, permanent_log = True, make_red = True):
    if message=="":
        return
    if permanent_log:
        LOG_NOTE(message)
    if make_red:
        message = '<font color="#FF0000">' + message + '</font>'
    try:
        SystemMessages.pushMessage(message, SystemMessages.SM_TYPE.Information)
    except:
        pass

def MYLOG(*args):
    LOG_NOTE("%s" % time.strftime('%Y-%m-%d %H:%M:%S'), *args)
    pass

def MYPPRINT(obj):
    import inspect, pprint
    if isinstance(obj, dict) or isinstance(obj, list) or isinstance(obj, tuple):
        pprint.pprint(obj, indent=1, width=180)
    elif hasattr(obj, '__call__'):
        pprint.pprint(inspect.getargspec(obj), indent=1, width=180)
    else:
        pprint.pprint(inspect.getmembers(obj), indent=1, width=180)

conf_file = None
res = ResMgr.openSection('../paths.xml')
sb = res['Paths']
vals = sb.values()[0:2]
for vl in vals:
    path = vl.asString + '/scripts/client/gui/mods/'
    if os.path.isdir(path):
        conf_file = path + 'mod_scheduler.json'
        if os.path.isfile(conf_file):
            with codecs.open(conf_file, 'r', 'utf-8-sig') as data_file:
                try:
                    print "config file: " + conf_file
                    config = json.load(data_file)
                    d = config.get("debug", False)
                except:
                    import sys
                    print "Error while loading %s: %s" % (conf_file, sys.exc_info()[0])
                finally:
                    break

def saveConfig():
    with open(conf_file, 'w') as data_file:
        try:
            json.dump(config, data_file, sort_keys=True, indent=4, separators=(',', ': '))
        except:
            print "Error while saving %s: %s" % (conf_file, sys.exc_info()[0])

def minuteLoop():
    BigWorld.callback(60, minuteLoop)
    if not g_appLoader.getSpaceID() == _SPACE_ID.LOBBY:
        return
    now = datetime.datetime.now()
    for timeKey, nextRun in schedule.iteritems():
        if nextRun < now:
            while nextRun < now:
                nextRun = nextRun + datetime.timedelta(days=1)
            schedule[timeKey] = nextRun
            entry = config["schedule"][timeKey]
            entry["nextRun"] = nextRun.strftime("%Y-%m-%d %H:%M")
            saveConfig()
            
            SystemMessages.pushMessage(entry["message"], SystemMessages.SM_TYPE.Warning)
            #showDialog(I18nInfoDialogMeta(key=entry["message"]))

if config["schedule"]:
    now = datetime.datetime.now()
    for timeKey, entry in config["schedule"].iteritems():
        if entry.setdefault("enabled", True):
            if not entry.get("nextRun", None):
                nextRun = datetime.datetime(now.year, now.month, now.day, int(timeKey.split(":")[0]), int(timeKey.split(":")[1]))
                if nextRun < now:
                    nextRun = nextRun + datetime.timedelta(days=1)
                entry["nextRun"] = nextRun.strftime("%Y-%m-%d %H:%M")
                saveConfig()
            else:
                nextRun = datetime.datetime.strptime(entry["nextRun"], "%Y-%m-%d %H:%M")
                if nextRun.hour != int(timeKey.split(":")[0]) or nextRun.minute != int(timeKey.split(":")[1]):
                    nextRun.replace(hour=int(timeKey.split(":")[0]), minute=int(timeKey.split(":")[1]))
            schedule[timeKey] = nextRun
    if schedule:
        if d: MYLOG(schedule)
        minuteLoop()
