print "Loading mod: friends_notifier v2016-02-26"
from debug_utils import LOG_NOTE
import ResMgr, json, os, codecs, BigWorld
from os.path import isfile, join
from messenger.proto.events import g_messengerEvents
from messenger.proto.xmpp.entities import XMPPUserEntity
from messenger.storage import storage_getter
from messenger.proto.shared_find_criteria import FriendsFindCriteria

config = {}
config_error = None
d = False

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

def MYLOG(*args):
    import time
    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_friends_notifier.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

mypath = ResMgr.openSection('../paths.xml')['Paths'].values()[0:2][0].asString + '/scripts/client/gui/mods/friends_notifier/'

online = {}

def checkGroup(user):
    name = config.get("group", "")
    return False if name and not name in user.getGroups() else True
    
def onUserStatusUpdated(user):
    if d: MYLOG(user)
    if isinstance(user, XMPPUserEntity):
        name = user.getName()
        if user.isOnline():
            if "friend" in user.getTags() and checkGroup(user):
              if not name in online:
                  online[name] = True
                  if d: MYLOG("%s (%s) is now online" % (user.getFullName(), name))
                  if isfile(join(mypath,name + ".mp3")):
                      playExtSound(name + ".mp3")
                  else:
                      playExtSound("online.mp3")
        else:
            if d: MYLOG("%s (%s) is now offline" % (user.getFullName(), name))
            try:
                del online[name]
            except KeyError:
                pass

def buildOnline():
    for friend in storage_getter('users')().getList(FriendsFindCriteria()):
        if friend.isOnline() and checkGroup(friend):
            online[friend.getName()] = True
    if d: MYLOG(online)
    g_messengerEvents.users.onUserStatusUpdated += onUserStatusUpdated

def onUsersListReceived(tags):
    if d: MYLOG("onUsersListReceived%s" % str(tags))
    if "friend" in tags and not "cached" in tags:
        BigWorld.callback(5, buildOnline)

g_messengerEvents.users.onUsersListReceived += onUsersListReceived
    
import subprocess

def playExtSound(mp3):
    try:
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = subprocess.SW_HIDE
        subprocess.Popen([mypath + "cmdmp3.exe",
                          mypath + mp3], startupinfo=startupinfo)
    except:
        pass
