# written by the TG scripter Colin Carley.
#
# current Maintainer: Defiant <mail@defiant.homedns.org>
#
# Self Destruct Countdown


import App
import MissionLib
import Bridge.BridgeUtils
import QuickBattle.QuickBattle
import Lib.LibEngineering

pBridge = App.g_kSetManager.GetSet('bridge')
g_pSaffi = App.CharacterClass_GetObject(pBridge, 'XO')
pSaffiMenu = Bridge.BridgeUtils.GetBridgeMenu('XO')
g_iCountdown = -1
MySelfDestructCaller = None
SDpPlayer = None
COUNT_TIME = Lib.LibEngineering.GetEngineeringNextEventType()
cTime = 0 # standard time
pDatabase = App.g_kLocalizationManager.Load("data/TGL/SelfDestructionCountdown.tgl")
pButtonSD = None
pButtonSDTimer = None

MODINFO = { "Author": "\"Defiant\" mail@defiant.homedns.org",
            "Download": "http://defiant.homedns.org/~erik/STBC/SelfDestruct/",
            "Version": "1.5",
            "License": "GPL",
            "Description": "This is adding a Countdown to the Self Destruction"
            }
            
# The Button
def init():
        global pButtonSD, pButtonSDTimer, cTime, COUNT_TIME
	g_pSaffi.AddPythonFuncHandlerForInstance(App.ET_INPUT_SELF_DESTRUCT, __name__ + ".MySelfDestructStart")
	pButtonSD = QuickBattle.QuickBattle.CreateBridgeMenuButton(App.TGString('Self Destruct'), App.ET_INPUT_SELF_DESTRUCT, 0, g_pSaffi)
        
	g_pSaffi.AddPythonFuncHandlerForInstance(COUNT_TIME, __name__ + ".SetSDTimer")
	pButtonSDTimer = QuickBattle.QuickBattle.CreateBridgeMenuButton(App.TGString("Time: " + str(cTime)), COUNT_TIME, 0, g_pSaffi)
        
        pMasterButtonSD = App.STMenu_CreateW(App.TGString("Self Destruct menu"))
        pSaffiMenu.PrependChild(pMasterButtonSD)
        pMasterButtonSD.PrependChild(pButtonSD)
	pMasterButtonSD.PrependChild(pButtonSDTimer)
        App.TopWindow_GetTopWindow().AddPythonFuncHandlerForInstance(App.ET_INPUT_SELF_DESTRUCT, __name__ + ".MySelfDestructStart")


def MySelfDestructStart(pObject, pEvent):
	global g_iCountdown, MySelfDestructCaller, SDpPlayer

	if (g_iCountdown == -1):
		# mySelfDestruct: Start
		
		# This makes sure we kill the right ship (when transporting on another)
		SDpPlayer = MissionLib.GetPlayer()
		if not (SDpPlayer):
			return
			
		MySelfDestruct()
	# Now test what Function is calling us
	elif (str(MySelfDestructCaller) == str(pEvent)):
		if (g_iCountdown != -2):
			# mySelfDestruct: Go on
			MySelfDestruct()
	else:
		if (g_iCountdown == -2):
			# resetting g_iCountdown
			g_iCountdown = -1
		else:
			# mySelfDestruct: Cancel
			CancelSelfDestruct()


def MySelfDestruct():
	global g_iCountdown, MySelfDestructCaller, cTime, g_pSaffi, pDatabase
	
	MySelfDestructCaller = None
	
	if (g_iCountdown == -1):
		# We are starting our countdown..
		g_iCountdown = cTime + 6
		# its 14 cause we need more time for auth...
	elif (g_iCountdown == 0):
                # We're dead!
	        FinallyDie()
        	return

	# Create an event - it's a thing that will call this function
	pTimerEvent = App.TGEvent_Create()
	pTimerEvent.SetEventType(App.ET_INPUT_SELF_DESTRUCT)
	pTimerEvent.SetDestination(App.TopWindow_GetTopWindow())

	SDCounterTime = 1.0
	
	# Create a timer - it's a thing that will wait for a given time,then do something
	pTimer = App.TGTimer_Create()
	pTimer.SetTimerStart(App.g_kUtopiaModule.GetGameTime() + SDCounterTime)
	pTimer.SetDelay(0)
	pTimer.SetDuration(0)
	pTimer.SetEvent(pTimerEvent)
	App.g_kTimerManager.AddTimer(pTimer)
	MySelfDestructCaller = pTimerEvent
	
	# And finally, call out the line..
	pCharacter = App.CharacterClass_Cast(App.g_kSetManager.GetSet("bridge").GetObject("XO"))
	if (pCharacter):
		# Needed some Custom Values cause Saffi is speaking too slow!
		if ( g_iCountdown == cTime + 6):
			pCharacter.SpeakLine(pCharacter.GetDatabase(),"SelfDestructStart")
		elif ( g_iCountdown == cTime + 5):
			pCharacter.SpeakLine(pCharacter.GetDatabase(),"SaffiCommand")
		elif ( g_iCountdown == 10 and cTime > 0):
			pCharacter.SpeakLine(pCharacter.GetDatabase(),"SelfDestruct10")
		elif ( g_iCountdown < 10 and cTime > 0):
			pCharacter.SpeakLine(pCharacter.GetDatabase(),"SelfDestruct" + str(g_iCountdown))
                elif (g_iCountdown > 10 and g_iCountdown%10 == 0):
                        pcString = pDatabase.GetString ("SelfDestructTime").GetCString ()
                        pSequence = App.TGSequence_Create()
                        pSequence.AppendAction(App.CharacterAction_Create(g_pSaffi, App.CharacterAction.AT_SAY_LINE, "SelfDestructTime" + str(g_iCountdown), None, 0, pDatabase))
                        pSequence.Play()

	g_iCountdown = g_iCountdown - 1
	

def FinallyDie():
	global g_iCountdown
	global SDpPlayer
	
	g_iCountdown = -1
	MySelfDestructCaller = None
	
	#print("Now we kill us")
	if hasattr(SDpPlayer, "GetHull"):
		SDpPlayer.DestroySystem(SDpPlayer.GetHull())


def CancelSelfDestruct():
	global g_iCountdown
	global SDpPlayer
	
	# set it to -2: lock it so all calls from MySelfDestruct() will land in /dev/null
	g_iCountdown = -2
	SDpPlayer = None
	
	pCharacter = App.CharacterClass_Cast(App.g_kSetManager.GetSet("bridge").GetObject("XO"))
	if (pCharacter):
		pCharacter.SpeakLine(pCharacter.GetDatabase(),"SelfDestructCancel")
		pCharacter.SpeakLine(pCharacter.GetDatabase(),"SaffiCommand")


def Restart():
	global g_iCountdown
	global SDpPlayer
	
	if ( g_iCountdown > -1 ):
		CancelSelfDestruct()
		SDpPlayer = None


def SetSDTimer(pObject, pEvent):
    global pButtonSDTimer, cTime, g_iCountdown
    if (g_iCountdown != -1):
        return
    cTime = cTime + 10
    if (cTime == 130):
        cTime = 0
    pButtonSDTimer.SetName(App.TGString("Time: " + str(cTime)))
