# RevolutionInit.py
#
# by jdog5000
# Version 2.2
 
# This file should be imported into CvCustomEventManager and the
# __init__ function then called from the event handler initilization
# spot using:
#
# RevolutionInit.RevolutionInit( self, configFileName )
#
# where configFileName is nominally "Revolution.ini".
 
from CvPythonExtensions import *
import CvUtil
import PyHelpers
import Popup as PyPopup
import CvConfigParser
import CvModName
import CvPath
# --------- Revolution mod -------------
import RevDefs
import RevEvents
import BarbarianCiv
import ChangePlayer
import Revolution
import Tester
import TechDiffusion
import StartAsMinors
import DynamicCivNames
import RevInstances
 
import os.path
 
gc = CyGlobalContext()
PyPlayer = PyHelpers.PyPlayer
PyInfo = PyHelpers.PyInfo
game = CyGame()
localText = CyTranslator()
 
class RevolutionInit :
 
    def __init__( self, customEM, configFileName = None ) :
 
        CvUtil.pyPrint("Initializing Revolution Mod")
 
        self.EventKeyDown = 6
        self.customEM = customEM
        self.configFileName = configFileName
 
        print "Mod name as obtained from DLL: %s" % game.getModName()
        self.configFileNameWithPath =  os.path.join(CvPath.installDir, game.getModName(), configFileName)
        print "Absolute path to the config file: %s" % self.configFileNameWithPath
 
        config = CvConfigParser.CvConfigParser(self.configFileNameWithPath)
        self.config = config
 
        self.bFoundConfig = config.getboolean("RevConfig", "FoundConfig", False)
        self.bShowActivePopup = config.getboolean("RevConfig", "ActivePopup", True)
 
        print "Config found: ", self.bFoundConfig
        print "Show active popup: ", self.bShowActivePopup
 
        self.revComponentsText = ""
 
        customEM.addEventHandler( "kbdEvent", self.onKbdEvent )
        customEM.addEventHandler( 'GameStart', self.onGameStart )
        customEM.addEventHandler( 'OnLoad', self.onGameLoad )
        #customEM.addEventHandler( 'Init', self.onInit )
 
        # Determine if game is already running and Python has just been reloaded
        if( game.isFinalInitialized() ) :
            print "Game initialized!"
            self.onGameLoad( None, self.bShowActivePopup )
 
 
 
    def onKbdEvent(self, argsList ):
        'keypress handler'
        eventType,key,mx,my,px,py = argsList
 
        if ( eventType == RevDefs.EventKeyDown ):
            theKey=int(key)
 
            # For debug or trial only
            if( theKey == int(InputTypes.KB_Q) and self.customEM.bShift and self.customEM.bCtrl ) :
                self.showActivePopup()
 
    def onInit( self, argsList ) :
        print "Init fired"
 
    def onGameStart( self, argsList ) :
 
        print "Gaming starting now"
 
        self.onGameLoad( None )
 
    def onGameLoad( self, argsList, bForceReinit = False, bShowPopup = True ) :
 
        # Remove any running mod components
        bDoUnInit = (bForceReinit or RevInstances.bIsInitialized)
        bDoInit = (bDoUnInit or not RevInstances.bIsInitialized)
 
        if( bDoUnInit ) :
            print "PY:  Uninitializing Revolution Mod components"
 
            if( not RevInstances.BarbarianCivInst == None ) :
                RevInstances.BarbarianCivInst.removeEventHandlers()
                RevInstances.BarbarianCivInst = None
            if( not RevInstances.RevolutionInst == None ) :
                RevEvents.removeEventHandlers()
                RevInstances.RevolutionInst.removeEventHandlers()
                RevInstances.RevolutionInst = None
            if( not RevInstances.DynamicCivNamesInst == None ) :
                RevInstances.DynamicCivNamesInst.removeEventHandlers()
                RevInstances.DynamicCivNamesInst = None
            if( not RevInstances.TechDiffusionInst == None ) :
                RevInstances.TechDiffusionInst.removeEventHandlers()
                RevInstances.TechDiffusionInst = None
 
            if( not RevInstances.TesterInst == None ) :
                RevInstances.TesterInst.removeEventHandlers()
                RevInstances.TesterInst = None
            if( not RevInstances.ChangePlayerInst == None ) :
                RevInstances.ChangePlayerInst.removeEventHandlers()
                RevInstances.ChangePlayerInst = None
 
            RevInstances.bIsInitialized = False
 
        # Initialize mod components
        if( bDoInit ) :
            print "PY:  Initializing Revolution Mod components"
            RevInstances.bIsInitialized = True
 
        # This component mainly contains test and debug routines
        if( bDoInit ) : RevInstances.TesterInst = Tester.Tester( self.customEM, self.config )
 
        revComponentsText = "Revolution mod running with the following components: <color=0,255,0,255>on<color=255,255,255,255>/<color=255,0,0,255>off\n"
 
        if( gc.isBARBARIAN_CIV() ):#self.config.getboolean("BarbarianCiv", "Enable", True) ) :
            if( bDoInit ) : RevInstances.BarbarianCivInst = BarbarianCiv.BarbarianCiv(self.customEM, self.config)
            revComponentsText += "<color=0,255,0,255>" + "\nBarbarianCiv"
        else :
            revComponentsText += "<color=255,0,0,255>" + "\nBarbarianCiv"
        if( self.config.getboolean("ChangePlayer", "Enable", False) ) :
            if( bDoInit ) : RevInstances.ChangePlayerInst = ChangePlayer.ChangePlayer(self.customEM, self.config)
            revComponentsText += "<color=0,255,0,255>" + "\nChangePlayer"
        else :
            revComponentsText += "<color=255,0,0,255>" + "\nChangePlayer"
        if( gc.isREVOLUTION_MOD() ):#self.config.getboolean("Revolution", "Enable", True) ) :
            if( bDoInit ) : 
                # RevEvents needs to service beginPlayerTurn events before Revolution
                RevEvents.init( self.customEM, self.config )
                RevInstances.RevolutionInst = Revolution.Revolution(self.customEM, self.config)
            revComponentsText += "<color=0,255,0,255>" + "\nRevolution"
        else :
            revComponentsText += "<color=255,0,0,255>" + "\nRevolution"
        if( gc.isTECH_DIFFUSION() ):#self.config.getboolean("TechDiffusion", "Enable", True) ) :
            if( bDoInit ) : RevInstances.TechDiffusionInst = TechDiffusion.TechDiffusion(self.customEM, self.config)
            revComponentsText += "<color=0,255,0,255>" + "\nTechDiffusion"
        else :
            revComponentsText += "<color=255,0,0,255>" + "\nTechDiffusion"
        if( gc.isSTART_AS_MINORS() ):
            if( bDoInit ) : StartAsMinors.init( self.customEM, self.config )
            revComponentsText += "<color=0,255,0,255>" + "\nStartAsMinors"
        else :
            revComponentsText += "<color=255,0,0,255>" + "\nStartAsMinors"
        if( gc.isDYNAMIC_CIV_NAMES() ):#self.config.getboolean("DynamicCivNames", "Enable", True) ) :
            if( bDoInit ) : RevInstances.DynamicCivNamesInst = DynamicCivNames.DynamicCivNames(self.customEM, self.config)
            revComponentsText += "<color=0,255,0,255>" + "\nDynamicCivNames"
        else :
            revComponentsText += "<color=255,0,0,255>" + "\nDynamicCivNames"
 
        revComponentsText += "<color=255,255,255,255>"
        self.revComponentsText = revComponentsText
 
        if( bShowPopup and self.bShowActivePopup ) :
            self.showActivePopup()
 
        if( not self.bFoundConfig ) :
            popup = PyPopup.PyPopup( )
            bodStr = "WARNING:  " + self.configFileName + " not found!  Revolution components using default settings."
            bodStr += "  Check mod installation directory, should be:\n\n" + CvPath.installActiveModDir
            bodStr += "\n\nOr:\n\n" + CvPath.userActiveModDir
            popup.setBodyString( bodStr )
            popup.launch()
 
        if( bDoInit ) :
            CyInterface().setDirty( InterfaceDirtyBits.MiscButtons_DIRTY_BIT, True )
            CyInterface().setDirty( InterfaceDirtyBits.CityScreen_DIRTY_BIT, True )
            CyInterface().setDirty( InterfaceDirtyBits.MiscButtons_DIRTY_BIT, True )
 
    def showActivePopup( self ) :
 
        revMaxCivs = self.config.getint("Revolution", "MaxCivs", gc.getMAX_CIV_PLAYERS())
        barbMaxCivs = self.config.getint("BarbarianCiv", "MaxCivs", gc.getMAX_CIV_PLAYERS())
        revDefaultNumPlayers = gc.getWorldInfo(gc.getMap().getWorldSize()).getDefaultPlayers()
 
        bodStr = self.revComponentsText
        bodStr += localText.getText("TXT_KEY_REV_MOD_MAX_CIVS_IN_DLL",( gc.getMAX_CIV_PLAYERS(), ))
        if( revMaxCivs > 0 and revMaxCivs < gc.getMAX_CIV_PLAYERS() ) :
            bodStr += localText.getText("TXT_KEY_REV_MOD_REVS_WILL_STOP_AT",( revMaxCivs, ))
        if( barbMaxCivs > 0 and barbMaxCivs < gc.getMAX_CIV_PLAYERS() ) :
            bodStr += localText.getText("TXT_KEY_REV_MOD_BARB_CIV_WILL_STOP_AT",( barbMaxCivs, ))
        bodStr += localText.getText("TXT_KEY_REV_MOD_TURNS_IN_GAME",( game.getMaxTurns(), ))
        bodStr += localText.getText("TXT_KEY_REV_MOD_DEFAULT_NUM_PLAYERS",( revDefaultNumPlayers, ))
 
        popup = PyPopup.PyPopup( )
        popup.setBodyString( bodStr )
        popup.launch()