print "Loading mod: minimap_tankview v2016-08-14 (http://forum.worldoftanks.eu/index.php?/topic/441147-)"
"""
originally: mEDI_S, UrAGAn, Thx @ Makct
extendedby: Krzysztof_Chodak aka Kodak
"""
import BigWorld, ResMgr, BattleReplay, Math, Vehicle, GUI, math, os, json
from debug_utils import LOG_NOTE
from gui.Scaleform.Minimap import Minimap
from gui.app_loader import g_appLoader
from PlayerEvents import g_playerEvents
from constants import ARENA_PERIOD, ARENA_BONUS_TYPE
from gui import DEPTH_OF_Aim, g_repeatKeyHandlers, GUI_SETTINGS
from gui.Scaleform.Flash import Flash
from game import convertKeyEvent
from functools import partial
from gui.battle_control import g_sessionProvider
from vehicle_systems.tankStructure import TankPartNames

minimapEntries = {}
eligible = {}
enemies = {}
config = None
minimap = None
playerVehicleID = None
myEventsAttached = False
toggleKey = 0
toggleStateOn = True
cw_mode = None

def MYLOGLIVE(message, permanent_log = True, make_red = True):
    from messenger import MessengerEntry
    if message=="":
        return
    if permanent_log:
        LOG_NOTE(message)
    if make_red:
        message = '<font color="#FF0000">' + message + '</font>'
    try:
        MessengerEntry.g_instance.gui.addClientMessage(message)
    except:
        pass

def MYLOG(*args):
    LOG_NOTE(os.path.basename(__file__), *args)

def MYPPRINT(obj):
    import inspect, pprint
    if isinstance(obj, dict) or isinstance(obj, list) or isinstance(obj, tuple):
        pprint.pprint(obj)
    elif hasattr(obj, '__call__'):
        pprint.pprint(inspect.getargspec(obj))
    else:
        pprint.pprint(inspect.getmembers(obj))
    
def myPe_onArenaPeriodChange(period = ARENA_PERIOD.BATTLE, *args):
    global minimap
    global playerVehicleID
    global myEventsAttached
    global cw_mode
    if period is ARENA_PERIOD.BATTLE:
        if not config['showInBattleReplay'] and BattleReplay.g_replayCtrl.isPlaying:
            #MYLOG('in a replay')
            return
        #MYLOG('in a battle')
        if g_appLoader.getDefBattleApp() is None:
            #MYLOG('no battleWindow yet, retrying in a sec')
            BigWorld.callback(1, myPe_onArenaPeriodChange)
            return
        player = BigWorld.player()
        arena = player.arena
        vehicles = arena.vehicles
        if player.isVehicleAlive:
            playerVehicleID = player.playerVehicleID
            if not 'SPG!' in vehicles[playerVehicleID]['vehicleType'].type.tags:
                #minimap = g_appLoader.getDefBattleApp().minimap
                cw_mode = arena.bonusType in [
                    ARENA_BONUS_TYPE.CLAN,
                    ARENA_BONUS_TYPE.EVENT_BATTLES,
                    ARENA_BONUS_TYPE.GLOBAL_MAP
                ]
                for vehicleID, desc in vehicles.items():
                    enemy = player.team is not desc['team']
                    if enemy:
                        enemies[vehicleID] = True
                    if not ((enemy and not config['showEnemy']) or playerVehicleID == vehicleID) and \
                        (player.team is not desc['team'] or config['showAllySPG'] and \
                         'SPG' in desc['vehicleType'].type.tags or config['showAllyTD'] and \
                        'AT-SPG' in desc['vehicleType'].type.tags or toggleStateOn == False):
                        eligible[vehicleID] = True
                        entity = BigWorld.entity(vehicleID)
                        if not entity is None and desc['isAlive'] == True and minimap:
                            minimapEntries[vehicleID] = minimap._Minimap__ownUI.addEntry(getEntry(vehicleID), minimap.zIndexManager.getVehicleIndex(vehicleID) - 50)
                            minimap._Minimap__ownUI.entryInvoke(minimapEntries[vehicleID], ('gotoAndStop', ['cursorNormal']))
                if not myEventsAttached:
                    player.onVehicleEnterWorld += myOnVehicleEnterWorld
                    player.onVehicleLeaveWorld += myOnVehicleLeaveWorld
                    arena.onVehicleKilled += myOnVehicleKilled
                    myEventsAttached = True
            else:
                cleanUp()
        else:
            cleanUp()
    elif period is ARENA_PERIOD.AFTERBATTLE:
        cleanUp()

def cleanUp():
    global minimap
    global playerVehicleID
    global myEventsAttached
    playerVehicleID = None
    if myEventsAttached:
        player = BigWorld.player()
        player.onVehicleEnterWorld -= myOnVehicleEnterWorld
        player.onVehicleLeaveWorld -= myOnVehicleLeaveWorld
        if player.arena:
            player.arena.onVehicleKilled -= myOnVehicleKilled
        myEventsAttached = False
    if minimap:
        for vehicleID in minimapEntries.iterkeys():
            minimap._Minimap__ownUI.delEntry(minimapEntries[vehicleID])
        minimap = None
    minimapEntries.clear()
    eligible.clear()
    enemies.clear()
    
def myOnVehicleEnterWorld(vehicle):
    if not vehicle.isAlive():
        return
    vehicleID = vehicle.id
    if (eligible.has_key(vehicleID) or cw_mode and isEligible(vehicleID)) and not minimapEntries.has_key(vehicleID) and minimap:
        minimapEntries[vehicleID] = minimap._Minimap__ownUI.addEntry(getEntry(vehicle), minimap.zIndexManager.getVehicleIndex(vehicleID) - 50)
        minimap._Minimap__ownUI.entryInvoke(minimapEntries[vehicleID], ('gotoAndStop', ['cursorNormal']))
    
def isEligible(vehicleID):
    player = BigWorld.player()
    arena = player.arena
    desc = arena.vehicles[vehicleID]
    enemy = player.team is not desc['team']
    if enemy:
        enemies[vehicleID] = True
    if not ((enemy and not config['showEnemy']) or playerVehicleID == vehicleID) and \
        (player.team is not desc['team'] or config['showAllySPG'] and \
         'SPG' in desc['vehicleType'].type.tags or config['showAllyTD'] and \
        'AT-SPG' in desc['vehicleType'].type.tags or toggleStateOn == False):
        eligible[vehicleID] = True
        return True
    return False
    
def myOnVehicleLeaveWorld(vehicle):
    vehicleID = vehicle.id
    #MYLOG('VehicleLeaveWorld: %s (%s)' % (vehicle.typeDescriptor.type.name, vehicleID))
    if minimapEntries.has_key(vehicleID):
        if minimap._Minimap__ownUI:
            minimap._Minimap__ownUI.delEntry(minimapEntries[vehicleID])
        minimapEntries.pop(vehicleID)

def myOnVehicleKilled(vehicleID, *args):
    #MYLOGLIVE('myOnVehicleKilled (%s, own %s)' % (vehicleID, playerVehicleID))
    if vehicleID == playerVehicleID:
        cleanUp()
        #MYLOGLIVE("Oh no! We've got killed :(")
    else:
        if minimapEntries.has_key(vehicleID):
            minimap._Minimap__ownUI.delEntry(minimapEntries[vehicleID])
            minimapEntries.pop(vehicleID)

def getEntry(vehicle):
    if not isinstance(vehicle, Vehicle.Vehicle):
        vehicle = BigWorld.entities[vehicle]
    matrix = vehicle.matrix
    #rotMatrix = vehicle.appearance.modelsDesc['gun']['model'].matrix
    rotMatrix = vehicle.appearance.compoundModel.node(TankPartNames.GUN)
    m = Math.WGTranslationOnlyMP()
    m.source = matrix
    mm = Math.WGCombinedMP()
    mm.translationSrc = m.source
    mm.rotationSrc = rotMatrix
    return mm

def myHandleRepeatKeyEvent(event):
    global toggleStateOn
    if GUI_SETTINGS.minimapSize:
        if event.key == toggleKey and event.repeatCount == 1:
            if toggleStateOn:
                toggleStateOn = False
                g_playerEvents.onArenaPeriodChange -= myPe_onArenaPeriodChange
                cleanUp()
                MYLOGLIVE(config.get("toggledOffMsg", ""), make_red=False)
            else:
                toggleStateOn = True
                g_playerEvents.onArenaPeriodChange += myPe_onArenaPeriodChange
                if not g_appLoader.getDefBattleApp() is None:
                    myPe_onArenaPeriodChange()
                MYLOGLIVE(config.get("toggledOnMsg", ""), make_red=False)
            config["toggleStateOn"] = toggleStateOn
            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])
            
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_minimap_tankview.json'
        if os.path.isfile(conf_file):
            with open(conf_file) as data_file:
                try:
                    config = json.load(data_file)
                except:
                    import sys
                    print "Error while loading %s: %s" % (conf_file, sys.exc_info()[0])
                finally:
                    break

d = False
if config:
    d = config.get("debug", False)
    toggleKey = config["toggleKeyCode"]
    if toggleKey > 0:
        g_repeatKeyHandlers.add(myHandleRepeatKeyEvent)
        toggleStateOn = config["toggleStateOn"]
    if toggleStateOn:
        g_playerEvents.onArenaPeriodChange += myPe_onArenaPeriodChange
if d:
    MYLOG(conf_file)
        
def myOnAvatarBecomeNonPlayer(*args):
    cleanUp()
    
g_playerEvents.onAvatarBecomeNonPlayer += myOnAvatarBecomeNonPlayer


def new_Minimap_start(self):
    global minimap
    old_Minimap_start(self)
    if d:
        MYLOG("we got minimap handle")
    minimap = self

from gui.Scaleform.Minimap import Minimap
old_Minimap_start = Minimap.start
print old_Minimap_start
Minimap.start = new_Minimap_start
