-- slotmachine.levelgen
MyObject = {}
function MyObject:New()
  local self = {}
  self.slotpos = nil
  self.slot1 = 0
  self.slot2 = 0
  self.slot3 = 0
  self.slot1obj = nil
  self.slot2obj = nil
  self.slot3obj = nil
  self.slottime = 0
  self.slotship = nil

  function self:onShipEnteredZone(ship, zone, zoneType, zoneId)
    if self.slottime == 0 then
      self.slotpos = zone:getPos()
      self.slotship = ship
      self.slottime = 2000
    end
  end


  function self:onTick(timePassed)

    if self.slottime == 0 then return end

    if self.slottime > timePassed then
      self.slottime = self.slottime - timePassed
    else
      self.slottime = 0
      local shippos = self.slotship:getPos()
      if shippos == nil then shippos = self.slotpos end
      if self.slot1 == self.slot2 and self.slot2 == self.slot3 then
        for a = 1, 13 * self.slot1 + 4 do
          local x = math.cos(a * 127) * 10
          local y = math.sin(a * 127) * 10
          local j = generateItem(self.slot1, shippos.x + x, shippos.y + y)
          j:setVel(point.new(x * 20, y * 20))
        end
      end
    end


    if self.slottime > 1000 + math.random(200) then
      self.slot1 = self.slot1 + 1
      if self.slot1 > 2 then self.slot1 = 0 end
      if self.slot1obj ~= nil then self.slot1obj:removeFromGame() end
      self.slot1obj = generateItem(self.slot1, self.slotpos.x - 200, self.slotpos.y - 150)
    end
    if self.slottime > 500 + math.random(200) then
      self.slot2 = self.slot2 + 1
      if self.slot2 > 2 then self.slot2 = 0 end
      if self.slot2obj ~= nil then self.slot2obj:removeFromGame() end
      self.slot2obj = generateItem(self.slot2, self.slotpos.x, self.slotpos.y - 150)
    end
    if self.slottime > 10 + math.random(200) then
      self.slot3 = self.slot3 + 1
      if self.slot3 > 2 then self.slot3 = 0 end
      if self.slot3obj ~= nil then self.slot3obj:removeFromGame() end
      self.slot3obj = generateItem(self.slot3, self.slotpos.x + 200, self.slotpos.y - 150)
    end
  end

  return self
end

slots = {}


function onShipEnteredZone(ship, zone, zoneType, zoneId)
  if zoneType == ObjType.Zone then
    if slots[zoneId] == nil then slots[zoneId] = MyObject:New() end
    slots[zoneId]:onShipEnteredZone(ship, zone, zoneType, zoneId)
  end
end

function generateItem(num, x, y)
  local obj1
  if     num == 0 then obj1 = Asteroid.new()
  elseif num == 1 then obj1 = Mine.new()
  elseif num == 2 then obj1 = FlagItem.new()
  end
  obj1:setPos(point.new(x, y))
  levelgen:addItem(obj1)
  return obj1
end

function onTick(timePassed)
  for index, slot in pairs(slots) do
    slots[index]:onTick(timePassed)
  end

end

function main()
  subscribe(Event.Tick)
  subscribe(Event.ShipEnteredZone)
end