-- HalfSnowball.levelgen
-- Snowball.levelgen
-- for December level contest

-- Going in the turret (with the zone) will grant the player the ability to shoot evil snowballs.
-- Note: Turret vs bots is a little buggy due to the fact that robots don't really die, they just disappear (I think)

function main()
   subscribe(Event.ShipEnteredZone)
   subscribe(Event.Tick)
   
   ourTeam = getOurTeam()
   occupiedTeam = -1
   turretPos = point.new(1224, 0) -- Where the player appears inside the turret
   turretBulletPos = point.new(1165, 0) -- Where the bullets show up
   
   turretZoneId = 589 -- ID
   specialModule = Module.Cloak
   
   turretDelay = 10
   currentTurretTime = turretDelay
   
   bulletVelocity = 2000
   bulletLifeTime = 1 -- In seconds
   allBullets = {} -- Array of resource items
   
   bulletHurtRange = 10000
   bulletHurt = 0.4
   bulletEnergyUsage = 0.3
   
   playerInTurret = nil -- Holds a playerInfo, since they stay the same during the whole game!
   turretDisoccupyDistance = 5000
   cloakEnergyUsage = 14 -- Constant found in shipItems.h
   cloakEnergyPerTick = (cloakEnergyUsage / 60) / 100
   
   areaP1 = point.new(0, -765)
   areaP2 = point.new(2040, 765)
   
   startingLoadout = {Module.Cloak, Module.Shield, Weapon.Phaser, Weapon.Burst, Weapon.Mine} -- Given to all players at the start
   Timer:scheduleOnce(sayWelcomeMessage, 1500)
end

function onShipEnteredZone(ship, zone)
   if(zone:getId()==turretZoneId and playerInTurret==nil and ship:getTeamIndex()==ourTeam) then -- Empty turret
      if(ship:getMountedItems(ObjType.Flag)[1]==nil) then -- Not carrying a flag
         occupyTurret(ship, zone)
      else
         levelgen:privateMsg("Can't get in turret with a flag!", ship:getPlayerInfo():getName())
      end
   end
end

function getOurTeam()
   return getTurretZone():getTeamIndex() -- From zone team
end

function getTurretZone()
   return bf:findObjectById(589) -- Really funny how I cannot give findObjectById() a variable holding the id, error: expected integer
end

function occupyTurret(ship, zone)
   ship:setPos(turretPos)
   zone:setTeam(occupiedTeam)
   
   playerInTurret = ship:getPlayerInfo()
end

function disoccupyTurret(zone)
   zone:setTeam(ourTeam)
   
   playerInTurret = nil
end

function sayWelcomeMessage()
   local allShips = {}
   
   allShips = bf:findAllObjects(ObjType.Ship)
   
   for i,v in ipairs(allShips) do
      if(v:getTeamIndex()==ourTeam) then
         v:setLoadoutNow(startingLoadout)
         levelgen:privateMsg("Cloak uses ZERO energy in right half!", v:getPlayerInfo():getName())
      end
   end
end

function updateTurret()
   local currentTime = os.clock()
   local indexesToRemove = {}
   
   local allShipsInArea = {}
   local bullet = nil
   
   allShipsInArea = bf:findAllObjects(ObjType.Ship, ObjType.Robot) -- Robot for the evil snowballs
   
   if(currentTurretTime>0) then
      currentTurretTime = currentTurretTime - 1
   end
   
   for i=#allBullets,1,-1 do -- http://stackoverflow.com/questions/12394841/safely-remove-items-from-an-array-table-while-iterating
      bullet = allBullets[i]
      if(bullet.launchTime~=nil and currentTime>=bullet.launchTime + bulletLifeTime) then
         bullet:removeFromGame()
         table.remove(allBullets, i)
      else
         for j,k in ipairs(allShipsInArea) do
            if(k:getTeamIndex()~=ourTeam and not k:isModActive(Module.Shield)) then -- Not using shield
            
               if(point.distSquared(k:getPos(), bullet:getPos())<=bulletHurtRange) then
                  k:setHealth(k:getHealth() - bulletHurt)
                  
                  bullet:removeFromGame()
                  table.remove(allBullets, i)
                  
                  break -- Break out of inner loop to make sure this bullet doesn't do anything else!
               end
            end
         end
      end
   end
end

function shootTurret(ship) -- Valid ship
   if(currentTurretTime==0) then
      currentTurretTime = turretDelay -- Reset time
      
      local bullet = ResourceItem.new(turretBulletPos)
      
      bullet:setVel(getBulletVelocity(ship))
      levelgen:addItem(bullet)
      
      bullet.launchTime = os.clock() -- WHAT? Object-oriented programming in LUA?
      
      ship:setEnergy(ship:getEnergy() - bulletEnergyUsage) -- When you are out of energy, you can't use cloak, so you can't shoot!
      
      table.insert(allBullets, bullet)
   end
end

function getBulletVelocity(ship) -- Get a point on a circle. The radius of this circle is the velocity, the angle, the angle of the ship.
   local shipAngle = ship:getAngle()
   local x = bulletVelocity * math.cos(shipAngle) -- http://stackoverflow.com/questions/839899/how-do-i-calculate-a-point-on-a-circle-s-circumference
   local y = bulletVelocity * math.sin(shipAngle)
   
   return point.new(x, y)
end

function onTick()
   local allShipsInArea = {}
   
   allShipsInArea = bf:findAllObjectsInArea(areaP1, areaP2, ObjType.Ship, ObjType.Robot) -- Robot for the evil snowballs
   
   for i,v in ipairs(allShipsInArea) do
      if(v:isModActive(specialModule) and v:getTeamIndex()==ourTeam) then
         v:setEnergy(v:getEnergy() + cloakEnergyPerTick) -- Cancel cloak energy usage
      end
   end
   
   updateTurret()
   
   if(playerInTurret~=nil) then
      local shipInTurret = playerInTurret:getShip()
      local shipInTurretPos = shipInTurret:getPos()
      
      if(shipInTurretPos~=nil and point.distSquared(shipInTurretPos, turretPos) >= turretDisoccupyDistance) then -- Too far away
         disoccupyTurret(getTurretZone())
      elseif(shipInTurret:isModActive(specialModule)) then
         shootTurret(shipInTurret)
      end
   end
end