import App
import Custom.QBautostart.Libs.LibEngineering
import MissionLib
import Foundation
import addship

MODINFO = {     "Author": "\"Defiant\" erik@vontaene.de",
                "Download": "http://defiant.homedns.org/~erik/STBC/addship/",
                "Version": "0.1",
                "License": "BSD",
                "Description": "Add extra Ships to BC",
                "needBridge": 0
            }
            

SHIPS_WINDOW_X_POS			= 0.0925
SHIPS_WINDOW_Y_POS			= 0.1
SHIPS_WINDOW_WIDTH			= 0.25
SHIPS_WINDOW_HEIGHT			= 1.0
SHIPS_WINDOW_BAR_THICKNESS		= 0.0291667
SHIPS_SUBPANE_WIDTH			= 0.22
ADD_FRIEND_BUTTON_X_POS			= 0.250025
ADD_FRIEND_BUTTON_Y_POS			= 0.56
ADD_FRIEND_BUTTON_WIDTH			= 0.2515625
ADD_FRIEND_BUTTON_HEIGHT		= 0.0354167
ADD_ENEMY_BUTTON_X_POS			= 0.250025
ADD_ENEMY_BUTTON_Y_POS			= 0.60
ADD_ENEMY_BUTTON_WIDTH			= 0.2515625
ADD_ENEMY_BUTTON_HEIGHT			= 0.0354167
DEL_BUTTON_X_POS			= 0.250025
DEL_BUTTON_Y_POS			= 0.64
DEL_BUTTON_WIDTH			= 0.2515625
DEL_BUTTON_HEIGHT			= 0.0354167
FRIEND_LIST_X_POS			= 0.5390625
FRIEND_LIST_Y_POS			= 0.0083333
ENEMY_LIST_X_POS			= 0.5390625
ENEMY_LIST_Y_POS			= 0.5020835
CLOSE_X_POS                             = 0.3
CLOSE_Y_POS                             = 0
START_X_POS                             = 0.3
START_Y_POS                             = 0.05
ET_SELECT_SHIP_TYPE                     = Custom.QBautostart.Libs.LibEngineering.GetEngineeringNextEventType()
ET_ADD_AS_FRIEND                        = Custom.QBautostart.Libs.LibEngineering.GetEngineeringNextEventType()
ET_ADD_AS_ENEMY                         = Custom.QBautostart.Libs.LibEngineering.GetEngineeringNextEventType()
ET_DELETE                               = Custom.QBautostart.Libs.LibEngineering.GetEngineeringNextEventType()
ET_SELECT_SHIP_IN_FRIENDLY_MENU         = Custom.QBautostart.Libs.LibEngineering.GetEngineeringNextEventType()
ET_SELECT_SHIP_IN_ENEMY_MENU            = Custom.QBautostart.Libs.LibEngineering.GetEngineeringNextEventType()
ET_CLOSE                                = Custom.QBautostart.Libs.LibEngineering.GetEngineeringNextEventType()
ET_START                                = Custom.QBautostart.Libs.LibEngineering.GetEngineeringNextEventType()
SelectedSpecies                         = 0
pAddShipsWindow                         = None
g_pAddFriendButton                      = None
g_pAddEnemyButton                       = None
ships_list = {}
groupEnemy = {}
groupFriendly = {}
FriendlyButton                          = None
EnemyButton                             = None
curShipInMenu                           = None
curMenuInMenu                           = None



def Delete(pObject, pEvent):
    global curMenuInMenu, curShipInMenu, groupFriendly, groupEnemy
    if (curMenuInMenu == "enemy"):
        i = -1
        check_i = 0
        while check_i < len(groupEnemy.keys()):
            i = i + 1
            if not groupEnemy.has_key(i):
                continue
            check_i = check_i + 1
            if (groupEnemy[i] == curShipInMenu):
                del groupEnemy[i]
                RebuildEnemyMenu()
                break
    elif (curMenuInMenu == "friendly"):
        i = -1
        check_i = 0
        while check_i < len(groupFriendly.keys()):
            i = i + 1
            if not groupFriendly.has_key(i):
                continue
            check_i = check_i + 1
            if (groupFriendly[i] == curShipInMenu):
                del groupFriendly[i]
                RebuildFriendlyMenu()
                break


def ShipInEnemyMenuSelect(pObject, pEvent):
    global curMenuInMenu, curShipInMenu
    curMenuInMenu = "enemy"
    curShipInMenu = pEvent.GetInt()
    

def ShipInFriendlyMenuSelect(pObject, pEvent):
    global curMenuInMenu, curShipInMenu
    curMenuInMenu = "friendly"
    curShipInMenu = pEvent.GetInt()


def RebuildEnemyMenu():
    global groupEnemy, pAddShipsWindow, ships_list, EnemyButton

    EnemyButton.KillChildren()
    i = -1
    check_i = 0
    while check_i < len(groupEnemy.keys()):
        i = i + 1
        if not groupEnemy.has_key(i):
            continue
        check_i = check_i + 1
        pEvent = App.TGIntEvent_Create()
        pEvent.SetEventType(ET_SELECT_SHIP_IN_ENEMY_MENU)
        pEvent.SetInt(groupEnemy[i])
        pEvent.SetDestination(pAddShipsWindow)
                
        Ship = ships_list[groupEnemy[i]][1]
        pButton = App.STButton_CreateW(App.TGString(Ship), pEvent)
        EnemyButton.AddChild(pButton)

    # resize Window
    EnemyButton.Open()


def RebuildFriendlyMenu():
    global groupFriendly, pAddShipsWindow, ships_list, FriendlyButton

    FriendlyButton.KillChildren()
    i = -1
    check_i = 0
    while check_i < len(groupFriendly.keys()):
        i = i + 1
        if not groupFriendly.has_key(i):
            continue
        check_i = check_i + 1
        pEvent = App.TGIntEvent_Create()
        pEvent.SetEventType(ET_SELECT_SHIP_IN_FRIENDLY_MENU)
        pEvent.SetInt(groupFriendly[i])
        pEvent.SetDestination(pAddShipsWindow)
                
        Ship = ships_list[groupFriendly[i]][1]
        pButton = App.STButton_CreateW(App.TGString(Ship), pEvent)
        FriendlyButton.AddChild(pButton)

    # resize Window
    FriendlyButton.Open()
    
    
def AddShipAsEnemy(pObject, pEvent):
    global SelectedSpecies, groupEnemy

    groupEnemy[len(groupEnemy.keys())] = SelectedSpecies
    RebuildEnemyMenu()


def AddShipAsFriend(pObject, pEvent):
    global SelectedSpecies, groupFriendly

    groupFriendly[len(groupFriendly.keys())] = SelectedSpecies
    RebuildFriendlyMenu()


def GenerateFriendMenu():
	global pAddShipsWindow, FriendlyButton
        
        FriendlyButton = App.STCharacterMenu_Create("Friendly")
	pAddShipsWindow.AddChild(FriendlyButton, FRIEND_LIST_X_POS, FRIEND_LIST_Y_POS)


def GenerateEnemyMenu():
	global pAddShipsWindow, EnemyButton

        EnemyButton = App.STCharacterMenu_Create("Enemy")
        pAddShipsWindow.AddChild(EnemyButton, ENEMY_LIST_X_POS, ENEMY_LIST_Y_POS)

    
def SelectShipType(pObject, pEvent):
        global g_pAddFriendButton, g_pAddEnemyButton, SelectedSpecies
        
        # Now we have a ship so we can enable these Buttons:
        g_pAddFriendButton.SetEnabled()
        g_pAddEnemyButton.SetEnabled()

	SelectedSpecies = pEvent.GetInt()

	pObject.CallNextHandler(pEvent)


def BuildShipSelectWindow():
        global pAddShipsWindow, ships_list

        pSubPane = App.STSubPane_Create(SHIPS_SUBPANE_WIDTH, 500.0, 0)
        
	# Create the buttons
        dict_sides = {}
        FdtnShips = Foundation.shipList
        if not FdtnShips:
                return
	for iIndex in range(len(FdtnShips)):
                Ship = FdtnShips[iIndex]
                ShipLongName = Ship.name
                mvSpecies = Ship.MenuGroup()
                if not mvSpecies:
                        continue
                ships_list[iIndex] = Ship.GetShipFile(), ShipLongName
                # Setup the event for when this button is clicked
		pEvent = App.TGIntEvent_Create()
		pEvent.SetEventType(ET_SELECT_SHIP_TYPE)
		pEvent.SetInt(iIndex)		# store the index so we know which button was clicked.
		pEvent.SetDestination(pAddShipsWindow)
                # Create the button.
		pButton = App.STButton_CreateW(App.TGString(ShipLongName), pEvent)
		pEvent.SetSource(pButton)
                if not dict_sides.has_key(mvSpecies):
                        dict_sides[mvSpecies] = App.STCharacterMenu_Create(mvSpecies)
                        pSubPane.AddChild(dict_sides[mvSpecies], 0, 0, 0)
                dict_sides[mvSpecies].AddChild(pButton, 0, 0, 0)

	pSubPane.Layout()
        pAddShipsWindow.AddChild(pSubPane)


def CreateWindowInterieur():
        global pAddShipsWindow, g_pAddFriendButton, g_pAddEnemyButton
        
        BuildShipSelectWindow()

	pEventAddAsFriendButton = App.TGEvent_Create()
	pEventAddAsFriendButton.SetEventType(ET_ADD_AS_FRIEND)
	pEventAddAsFriendButton.SetDestination(pAddShipsWindow)
	
	pEventAddAsEnemyButton = App.TGEvent_Create()
	pEventAddAsEnemyButton.SetEventType(ET_ADD_AS_ENEMY)
	pEventAddAsEnemyButton.SetDestination(pAddShipsWindow)
	
	pEventDelete = App.TGEvent_Create()
	pEventDelete.SetEventType(ET_DELETE)
	pEventDelete.SetDestination(pAddShipsWindow)

        # Create a button to add the currently selected ship to the list of friendlies
        g_pAddFriendButton = App.STRoundedButton_CreateW(App.TGString("Add as friend"), pEventAddAsFriendButton, ADD_FRIEND_BUTTON_WIDTH, ADD_FRIEND_BUTTON_HEIGHT, 1)
        g_pAddFriendButton.SetDisabled() # So that you can't add a ship 'til one has been selected
        g_pAddFriendButton.SetNormalColor(App.g_kMainMenuButtonColor)
        g_pAddFriendButton.SetHighlightedColor(App.g_kMainMenuButtonHighlightedColor)
        g_pAddFriendButton.SetSelectedColor(App.g_kMainMenuButtonSelectedColor)
        g_pAddFriendButton.SetColorBasedOnFlags()
        pAddShipsWindow.AddChild(g_pAddFriendButton, ADD_FRIEND_BUTTON_X_POS, ADD_FRIEND_BUTTON_Y_POS)


	# Create a button to add the currently selected ship to the list of enemies
	g_pAddEnemyButton = App.STRoundedButton_CreateW(App.TGString("Add as enemy"), pEventAddAsEnemyButton, ADD_ENEMY_BUTTON_WIDTH, ADD_ENEMY_BUTTON_HEIGHT, 1)
	g_pAddEnemyButton.SetDisabled() # So that you can't add a ship 'til one has been selected
	g_pAddEnemyButton.SetNormalColor(App.g_kMainMenuButtonColor)
	g_pAddEnemyButton.SetHighlightedColor(App.g_kMainMenuButtonHighlightedColor)
	g_pAddEnemyButton.SetSelectedColor(App.g_kMainMenuButtonSelectedColor)
	g_pAddEnemyButton.SetColorBasedOnFlags()
	pAddShipsWindow.AddChild(g_pAddEnemyButton, ADD_ENEMY_BUTTON_X_POS, ADD_ENEMY_BUTTON_Y_POS)

	g_pDeleteButton = App.STRoundedButton_CreateW(App.TGString("Delete"), pEventDelete, DEL_BUTTON_WIDTH, DEL_BUTTON_HEIGHT, 1)
	g_pDeleteButton.SetNormalColor(App.g_kQuickBattleBrightRed)
	pAddShipsWindow.AddChild(g_pDeleteButton, DEL_BUTTON_X_POS, DEL_BUTTON_Y_POS)

        GenerateFriendMenu()
        GenerateEnemyMenu()
        
        pEvent = App.TGIntEvent_Create()
        pEvent.SetEventType(ET_CLOSE)
        pEvent.SetDestination(pAddShipsWindow)
        pEvent.SetInt(0)
        pButton = App.STRoundedButton_CreateW(App.TGString("Close"), pEvent, 0.13125, 0.034583)
        pAddShipsWindow.AddChild(pButton, CLOSE_X_POS, CLOSE_Y_POS, 0)

        pEvent = App.TGIntEvent_Create()
        pEvent.SetEventType(ET_START)
        pEvent.SetDestination(pAddShipsWindow)
        pEvent.SetInt(0)
        pButton = App.STRoundedButton_CreateW(App.TGString("Start"), pEvent, 0.13125, 0.034583)
        pAddShipsWindow.AddChild(pButton, START_X_POS, START_Y_POS, 0)


def AddShips(pObject, pEvent):
        global pAddShipsWindow
        if not pAddShipsWindow:
                return
        pTacticalControlWindow = App.TacticalControlWindow_GetTacticalControlWindow()
        if pAddShipsWindow.IsVisible():
                pTacticalControlWindow.MoveToBack(pAddShipsWindow)
                pAddShipsWindow.SetNotVisible()
        else:
                pAddShipsWindow.SetVisible()
                pTacticalControlWindow.MoveToFront(pAddShipsWindow)
                # Not so agressiv to the front - only give us problems!
                pTacticalControlWindow.MoveTowardsBack(pAddShipsWindow)
                
        
# handle mouse clicks in empty space
def PassMouse(pWindow, pEvent):
        pWindow.CallNextHandler(pEvent)

        if pEvent.EventHandled() == 0:
                pEvent.SetHandled()

def addshiphelper(pObject, pEvent):
        global ships_list, groupFriendly, groupEnemy
        for i in groupFriendly.keys():
                ship = ships_list[groupFriendly[i]][0]
                print("add friendly: %s") % (ship)
                addship.friendly(ship)
        for i in groupEnemy.keys():
                ship = ships_list[groupEnemy[i]][0]
                print("add enemy: %s") % (ship)
                addship.enemy(ship)
        groupFriendly = {}
        groupEnemy = {}
        RebuildEnemyMenu()
        RebuildFriendlyMenu()
        AddShips(pObject, pEvent)


def CreateAddShipsWindow(pObject=None, pEvent=None):
        global pAddShipsWindow
        
        # Create the Engineering extra Window:
        pAddShipsWindow = App.STStylizedWindow_CreateW("StylizedWindow", "NoMinimize", App.TGString("Add ships Window"), 0.0, 0.0, None, 1, 0.8, 0.8, App.g_kMainMenuBorderMainColor)
        pTacticalControlWindow = App.TacticalControlWindow_GetTacticalControlWindow()
        pTacticalControlWindow.AddChild(pAddShipsWindow, 0.1, 0.1)

        pAddShipsWindow.AddPythonFuncHandlerForInstance(App.ET_MOUSE, __name__ + ".PassMouse")
        pAddShipsWindow.SetNotVisible()
        
        CreateWindowInterieur()

        pBridge = App.g_kSetManager.GetSet("bridge")
        if pBridge:
                g_pXO = App.CharacterClass_GetObject(pBridge, "XO")
                g_pXO.AddPythonFuncHandlerForInstance(App.ET_CHARACTER_MENU, __name__ + ".WindowClose")
        pAddShipsWindow.AddPythonFuncHandlerForInstance(ET_SELECT_SHIP_TYPE, __name__ + ".SelectShipType")
        pAddShipsWindow.AddPythonFuncHandlerForInstance(ET_ADD_AS_ENEMY, __name__ + ".AddShipAsEnemy")
        pAddShipsWindow.AddPythonFuncHandlerForInstance(ET_ADD_AS_FRIEND, __name__ + ".AddShipAsFriend")
        pAddShipsWindow.AddPythonFuncHandlerForInstance(ET_DELETE, __name__ + ".Delete")
        pAddShipsWindow.AddPythonFuncHandlerForInstance(ET_SELECT_SHIP_IN_FRIENDLY_MENU, __name__ + ".ShipInFriendlyMenuSelect")
        pAddShipsWindow.AddPythonFuncHandlerForInstance(ET_SELECT_SHIP_IN_ENEMY_MENU, __name__ + ".ShipInEnemyMenuSelect")
        pAddShipsWindow.AddPythonFuncHandlerForInstance(ET_CLOSE, __name__ + ".AddShips")
        pAddShipsWindow.AddPythonFuncHandlerForInstance(ET_START, __name__ + ".addshiphelper")
        
        
def WindowClose(pObject, pEvent):
        global pAddShipsWindow

        if not pAddShipsWindow:
                return

        pTacticalControlWindow = App.TacticalControlWindow_GetTacticalControlWindow()
        if pAddShipsWindow.IsVisible():
                pTacticalControlWindow.MoveToBack(pAddShipsWindow)
                pAddShipsWindow.SetNotVisible()

        pObject.CallNextHandler(pEvent)
        

def init():
        if App.g_kUtopiaModule.IsMultiplayer() and not App.g_kUtopiaModule.IsHost():
                return
        Custom.QBautostart.Libs.LibEngineering.CreateMenuButton("Add ships", "XO", __name__ + ".AddShips")
        MissionLib.CreateTimer(Custom.QBautostart.Libs.LibEngineering.GetEngineeringNextEventType(), __name__ + ".CreateAddShipsWindow", App.g_kUtopiaModule.GetGameTime() + 2.0, 0, 0)


def exit():
        global pAddShipsWindow
        if pAddShipsWindow:
                pAddShipsWindow.KillChildren()
                pTacticalControlWindow = App.TacticalControlWindow_GetTacticalControlWindow()
                pTacticalControlWindow.DeleteChild(pAddShipsWindow)
