import universe
import vsrandom
import Vector
import launch
import faction_ships
import Director
import unit
import VS
import universe


CARGOS = ['Pets','Artwork','Construction', "Software", "Liquor", "Furs", "Grain", "Generic_Foods",
          'Advanced_Fuels','Communications','Computers','Factory_Equipment', "Iron", "Movies",
          'Holographics','Home_Appliances','Medical_Equipment', 'Books',
          'Pre_Fabs','Plastics','Robot_Workers','Textiles', "Luxury_Foods",
          'Mining_Equipment','Food_Dispensers', "PlayThing_(tm)", "Weaponry",
          'Home_Entertainment','Tungsten','Wood', "Space_Salvage", "Space_Salvage", "Space_Salvage"]
       
       
def chooseDestSystemName( systemNamesList):
    numSystems = len( systemNamesList)
    if numSystems == 1:
        return systemNamesList[0]
    if numSystems == 2:
        if vsrandom.random() > .33:
            return systemNamesList[0]
        return systemNamesList[1]
    # 3 or more
    #print "PODXXbou num2: " + str( vsrandom.randrange( 1, numSystems))
    if vsrandom.random() > .5:
        return systemNamesList[0]
    return systemNamesList[ vsrandom.randrange( 1, numSystems) ]


class bounty_pod (Director.Mission):
    def __init__ ( self, creds, enemyFaction, enemyShipTypesList, systemNamesList):
        Director.Mission.__init__ ( self)
        self.you = VS.getPlayer()
        self.creds = creds
        self.enemyFaction = enemyFaction
        self.enemyShipTypesList = enemyShipTypesList
        self.destSystemName = chooseDestSystemName( systemNamesList)
        print "PODXXbou destSystemName: " + self.destSystemName

        self.missionStage = "searchingTheVictim"
        self.destNavpoint = None
        self.radarRange = faction_ships.calcRadarRange( self.you)

        self.enemyGreetTime = 10000000
        self.enemyShips = []
        self.crippledShip = None

        self.objDestroyVictim = -1
        searchText = "Go to "
        for nextSystemName in systemNamesList:
            if len( searchText) > 6:
                searchText += ", "
            searchText += nextSystemName[7:]
        searchText += "."
        self.objSearchSystems = VS.addObjective( searchText)
        

    def payOffMission( self):
        self.you.addCredits( self.creds)
        VS.terminateMission( 1)


    def launchEnemies( self):
        launchAroundUnit = self.destNavpoint
        for nextShipType in self.enemyShipTypesList:
            L = launch.Launch()
            L.fg = "Shadow"
            L.faction = self.enemyFaction
            L.type = nextShipType
            L.num = 1
            L.ai = "default"
            if launchAroundUnit == self.destNavpoint:
                L.minradius = 500
                L.maxradius = 700
            else:
                L.minradius = 200
                L.maxradius = 400
            enemy = L.launch( launchAroundUnit)
            enemy.SetTarget( self.you)
            enemy.setFgDirective( "A.")
            self.enemyShips.append( enemy)
            #print "PODXXbou next enemy: " + enemy.getName()
            if launchAroundUnit == self.destNavpoint:
                launchAroundUnit = enemy
            else:
                enemy.setFlightgroupLeader( launchAroundUnit)
    
    
    def launchRandomRemnants( self):
        launchAroundUnit = self.destNavpoint
        numcargos = vsrandom.randrange( 2, 4)
        for i in range( numcargos):
            L = launch.Launch()
            L.fg = "Remnants"
            L.faction = "upgrades"
            L.type = CARGOS[ vsrandom.randrange( 0, len( CARGOS))]
            L.num = 1
            L.ai = 'default'
            if launchAroundUnit == self.destNavpoint:
                L.minradius = 750
                L.maxradius = 1250
            else:
                L.minradius = 100
                L.maxradius = 150
            remnant = L.launch( launchAroundUnit)
            #remnant.SetMass( 4)
            remnant.SetHull( 5)
            if launchAroundUnit == self.destNavpoint:
                launchAroundUnit = remnant
        if vsrandom.random() > .5:
            eject = launch.launch_wave_around_area( "Pilot", "upgrades", "eject", "printhello.py", 1, 100, 150, launchAroundUnit.Position())
            eject.setName( "Pilot")
            eject.setFullname( "Pilot")
            eject.SetHull( vsrandom.randrange( 10, 35))
            
    
    def launchCrippledShip( self, faction):
        L = launch.Launch()
        L.fg = "Crippled"
        L.faction = faction
        if faction == "merchant":
            shipTypes = [ "tarsus", "tarsus", "galaxy", "drayman.toth"]
        elif faction == "militia":
            shipTypes = [ "talon", "gladius", "gladius"]
        else:
            return
        L.type = shipTypes[ vsrandom.randrange( 0, len( shipTypes))]
        L.num = 1
        L.ai = "sitting_duck"
        L.minradius = 300
        L.maxradius = 400
        self.crippledShip = L.launch( self.enemyShips[0])
        
        self.enemyShips[0].SetTarget( self.crippledShip)
        
        self.crippledShip.DisableTurretAI()
        self.crippledShip.SetTarget( self.destNavpoint)
        self.crippledShip.setFgDirective( "f")
        if L.type in ["galaxy", "drayman.toth"]:
            self.crippledShip.leach( 0.1, 0.1, 0)    # def leach(self,XshieldPercent,YrechargePercent,ZenergyPercent)
        if L.type == "drayman.toth":
            self.crippledShip.setName( "Drayman")
            self.crippledShip.setFullname( "Drayman")
        
        # putting the ship to an observable spot
        import escort_pod
        if self.you.getDistance( self.crippledShip) < 1500:
            cpos = self.crippledShip.Position()
        elif self.you.getDistance( self.enemyShips[0]) - 400 < self.radarRange:
            cpos = escort_pod.calcCatchupPosition( self.enemyShips[0].Position(), self.you.Position(), vsrandom.randrange( 300, 400))
        else:
            cpos = escort_pod.calcCatchupPosition( self.you.Position(), self.enemyShips[0].Position(), self.radarRange)
        self.crippledShip.SetPosition( VS.SafeEntrancePoint( cpos, self.crippledShip.rSize()))

    
    def setDestroyVictimObjective( self):
        mainUnitName = unit.getUnitFullName( self.enemyShips[0], False)
        colonIndex = mainUnitName.find( ":")
        if colonIndex != -1:
            mainUnitName = mainUnitName[0:colonIndex].capitalize()
        commaIndex = mainUnitName.find(".")
        if commaIndex != -1:
            mainUnitName = mainUnitName[0:commaIndex]
        
        objText = "Destroy "
        if self.enemyFaction <> "unknown":
            objText += self.enemyFaction.capitalize() + " "
        objText += mainUnitName
        if len( self.enemyShips) > 1:
            objText += " and the escort."
        else:
            objText += "."
        self.objDestroyVictim = VS.addObjective( objText)
        VS.setCompleteness( self.objDestroyVictim, -1.0)
    
    
    def untrackDeadEnemies( self):
        i = len( self.enemyShips) - 1
        while i >= 0:
            if self.enemyShips[i].isNull():
                del self.enemyShips[i]
            i -= 1
        
        
    def cleanTheArea( self, navpoint):
        iter = VS.getUnitList()
        while iter.notDone():
            un = iter.current()
            if navpoint.getSignificantDistance( un) < 2500:
                print "PODXXbou cleaning, next nearby unit: " + un.getName()
                if un.isSignificant() or un.isSun() or un == self.you or un.getName().find( "escortee") > 0:
                    pass
                else:
                    print "PODXXbou cleaned the unit"
                    #VS.addObjective( "Cleaned: " + un.getName())   #XXX
                    un.Kill()
            iter.advance()

    
    def Execute( self):
        if not self.you:
            VS.terminateMission( 0)
            return
        if VS.GetGameTime() >= self.enemyGreetTime and self.you.getDistance( self.enemyShips[0]) < self.radarRange:
            self.enemyGreetTime = 10000000
            universe.greet( universe.getRandomGreeting( self.enemyFaction), self.enemyShips[0], self.you)
       
        if self.missionStage == "searchingTheVictim":
            if VS.getSystemFile() <> self.destSystemName:
                return
            if self.destNavpoint == None:
                navpoints = universe.significantUnits()
                self.destNavpoint = navpoints[ vsrandom.randrange( 0, len( navpoints))]
                print "PODXXbou destNavpoint: " + self.destNavpoint.getName()
                
            if self.you.getDistance( self.destNavpoint) < 2000:
                self.cleanTheArea( self.destNavpoint)
                self.launchEnemies()
                
                extraLaunchChance = vsrandom.random()
                if extraLaunchChance < .25 and self.enemyShipTypesList[0] <> "galaxy.pirpar":
                    self.launchRandomRemnants()
                elif extraLaunchChance < .5:
                    factions = ["militia"]
                    if self.enemyShipTypesList[0] <> "galaxy.pirpar":
                        factions.append( "merchant")
                    self.launchCrippledShip( factions[ vsrandom.randrange( 0, len( factions))])
                    
                self.enemyGreetTime = VS.GetGameTime() + 6
                self.setDestroyVictimObjective()
                VS.setCompleteness( self.objSearchSystems, 1.0)
                self.missionStage = "fighting"
            return
            
        if self.missionStage == "fighting":
            self.untrackDeadEnemies()
            if len( self.enemyShips) == 0:
                self.payOffMission()
                return


