print "Loading mod: tidy_messenger v2015-12-13 (http://forum.worldoftanks.eu/index.php?/topic/496784-)"
from debug_utils import LOG_NOTE
from helpers import getClientLanguage
import ResMgr, os, json, codecs, re, time

config = {}
filterMsgByPattern = None
d = False

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)

from gui.SystemMessages import SM_TYPE

def getTypeName(msgType):
    if isinstance(msgType, (int, long)):
        return SM_TYPE[msgType].name()
    else:
        return msgType.name()

def isBattle(data):
    result = False
    try:
        result = ("isEvent" in data.keys())
    except:
        pass
    finally:
        if d:
            LOG_NOTE("isBattle=%s" % result)
        return result

def filteredOut(message, msgType, *args):
    if d:
        #import traceback
        #traceback.print_stack()
        LOG_NOTE("message=%s, msgType=%s %s" % (message, msgType, str(args)))
    if msgType in config.get("filterMsgTypes", []):
        if d:
            LOG_NOTE("filtered out by type")
        return True
    if message and isinstance(message, basestring):
        if message.startswith("#"):
            if message in config.get("filterMsgByIds", []):
                if d:
                    LOG_NOTE("filtered out by id")
                return True
        if filterMsgByPattern:
            m = filterMsgByPattern.search(message)
            if m:
                if d:
                    LOG_NOTE("filtered out by '%s'" % m.group(0))
                return True
    return False

from messenger.proto.bw.ServiceChannelManager import ServiceChannelManager
from messenger.proto.bw.wrappers import ServiceChannelMessage

def ServiceChannelManager_pushClientSysMessage(self, message, msgType, **kwargs):
    if filteredOut(message, getTypeName(msgType), "ServiceChannelManager_pushClientSysMessage") == False:
        return old_ServiceChannelManager_pushClientSysMessage(self, message, msgType, **kwargs)

old_ServiceChannelManager_pushClientSysMessage = ServiceChannelManager.pushClientSysMessage
ServiceChannelManager.pushClientSysMessage = ServiceChannelManager_pushClientSysMessage

def ServiceChannelManager_pushClientMessage(self, message, msgType, isAlert = False, auxData = None):
    if filteredOut(message, getTypeName(msgType), "ServiceChannelManager_pushClientMessage", auxData) == False:
        return old_ServiceChannelManager_pushClientMessage(self, message, msgType, isAlert, auxData)

old_ServiceChannelManager_pushClientMessage = ServiceChannelManager.pushClientMessage
ServiceChannelManager.pushClientMessage = ServiceChannelManager_pushClientMessage

def ServiceChannelManager_onReceiveSysMessage(self, chatAction):
    message = ServiceChannelMessage.fromChatAction(chatAction)
    msgType = SM_TYPE[message.type]
    if msgType is None:
        if d:
            LOG_NOTE("ServiceChannelManager_onReceiveSysMessage unknown message type (%d)" % message.type)
        msgType = str(message.type)
    else:
        msgType = msgType.name()
    if filteredOut(None, msgType, "ServiceChannelManager_onReceiveSysMessage", message) == False:
        return old_ServiceChannelManager_onReceiveSysMessage(self, chatAction)

old_ServiceChannelManager_onReceiveSysMessage = ServiceChannelManager.onReceiveSysMessage
ServiceChannelManager.onReceiveSysMessage = ServiceChannelManager_onReceiveSysMessage

def ServiceChannelManager_onReceivePersonalSysMessage(self, chatAction):
    message = ServiceChannelMessage.fromChatAction(chatAction)
    msgType = SM_TYPE[message.type]
    if msgType is None:
        if d:
            LOG_NOTE("ServiceChannelManager_onReceivePersonalSysMessage unknown message type (%d)" % message.type)
        msgType = str(message.type)
    else:
        msgType = msgType.name()
    if isBattle(message.data) or filteredOut(None, msgType, "ServiceChannelManager_onReceivePersonalSysMessage", message) == False:
        return old_ServiceChannelManager_onReceivePersonalSysMessage(self, chatAction)

old_ServiceChannelManager_onReceivePersonalSysMessage = ServiceChannelManager.onReceivePersonalSysMessage
ServiceChannelManager.onReceivePersonalSysMessage = ServiceChannelManager_onReceivePersonalSysMessage

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_tidy_messenger.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)
                    v0 = config.get("filterMsgByPattern", {}).get("common", None)
                    vl = config.get("filterMsgByPattern", {}).get(getClientLanguage(), None)
                    if v0:                        
                        if vl:
                            filterMsgByPattern = re.compile(v0 + "|" + vl)
                        else:
                            filterMsgByPattern = re.compile(v0)
                    else:
                        if vl:
                            filterMsgByPattern = re.compile(vl)
                except:
                    import sys
                    print "Error while loading %s: %s" % (conf_file, sys.exc_info()[0])
                finally:
                    break

from gui.shared import events, g_eventBus
from gui.shared.utils.decorators import dialog
from gui import DialogsInterface

@dialog
def my_showDialog(meta, callback):
    key = None
    if hasattr(meta, "_key"):
        key = meta._key
    if not key and hasattr(meta, "_meta") and meta._meta and hasattr(meta._meta, "_key"):
        key = meta._meta._key
    if d:
        LOG_NOTE("showDialog(key=%s, title=%s)" % (key, meta.getTitle()))
    if not key:
        key = meta.getTitle()
    if key in config.get("autoConfirmDialogs", []):
        #import traceback
        #traceback.print_stack()
        callback(True)
    elif key in config.get("autoCancelDialogs", []):
        callback(False)
    else:
        g_eventBus.handleEvent(events.ShowDialogEvent(meta, callback))

DialogsInterface.showDialog = my_showDialog


from gui.prb_control.invites import InvitesManager

def __pe_onPrebattleInvitesStatus(self, dbID, name, status):
    if status != PREBATTLE_INVITE_STATUS.OK:
        statusName = PREBATTLE_INVITE_STATUS_NAMES[status]
        MYLOG(statusName)
        SystemMessages.pushI18nMessage('#system_messages:invite/status/%s' % statusName, name=name, type=SystemMessages.SM_TYPE.Warning)

InvitesManager._InvitesManager__pe_onPrebattleInvitesStatus = __pe_onPrebattleInvitesStatus

from gui.Scaleform.SystemMessagesInterface import SystemMessagesInterface

def new_SystemMessagesInterface_pushI18nMessage(self, key, *args, **kwargs):
    if not filteredOut(key, None):
        old_SystemMessagesInterface_pushI18nMessage(self, key, *args, **kwargs)

old_SystemMessagesInterface_pushI18nMessage = SystemMessagesInterface.pushI18nMessage
SystemMessagesInterface.pushI18nMessage = new_SystemMessagesInterface_pushI18nMessage


from notification.listeners import PrbInvitesListener
from notification.settings import NOTIFICATION_TYPE
from notification.decorators import PrbInviteDecorator

def new_PrbInvitesListener__addInvites(self):
    if (d):
        MYLOG("PrbInvitesListener.__addInvites")
    model = self._model()
    if model is None:
        return
    else:
        model.removeNotificationsByType(NOTIFICATION_TYPE.INVITE)
        #invites = self.prbInvites.getReceivedInvites()
        invites = self.prbInvites.getInvites(incoming=True, onlyActive=True)
        invites = sorted(invites, cmp=lambda invite, other: cmp(invite.createTime, other.createTime))
        for invite in invites:
            model.addNotification(PrbInviteDecorator(invite))

        return

old_PrbInvitesListener__addInvites = PrbInvitesListener._PrbInvitesListener__addInvites
PrbInvitesListener._PrbInvitesListener__addInvites = new_PrbInvitesListener__addInvites

from notification.listeners import ClubsInvitesListener
from notification.decorators import ClubInviteDecorator
import operator
from gui.shared.utils import showInvitationInWindowsBar

def new_ClubsInvitesListener__addClubInvites(self):
    model = self._model()
    profile = self.clubsCtrl.getProfile()
    if model is None or not profile.isInvitesAvailable():
        return
    else:
        model.removeNotificationsByType(NOTIFICATION_TYPE.CLUB_INVITE)
        invites = profile.getInvites().values()
        invites = sorted(invites, cmp=lambda invite, other: cmp(invite.getTimestamp(), other.getTimestamp()))
        activeInvites = filter(operator.methodcaller('isActive'), invites)
        if len(activeInvites):
            showInvitationInWindowsBar()
        for invite in activeInvites: #invites:
            model.addNotification(ClubInviteDecorator(invite))

        return

old_ClubsInvitesListener__addClubInvites = ClubsInvitesListener._ClubsInvitesListener__addClubInvites
ClubsInvitesListener._ClubsInvitesListener__addClubInvites = new_ClubsInvitesListener__addClubInvites
