--[[
  Update 1.9.06 should implement City.playSound function which would allow for location based sound.
  In addition, it would solve the issues with leaveCity() and leaveStage() events.
]]

local red,green,blue, bx, by, buildingDraft, songDraft

function script:init()
  buildingDraft = Draft.getDraft("bluepickle.plugin.meme.building00")
  songDraft = Draft.getDraft("bluepickle.plugin.meme.song")
end

function script:update()
  math.randomseed(os.time()*10)
  red = 256 - math.random(0,256)
  green = 256 - math.random(0,256)
  blue = 256 - math.random(0,256)
end

function script:draw(tileX,tileY)
  if Tile.isBuildingInConstruction(tileX, tileY) then return end
  Drawing.setColor(red,green,blue)
  Drawing.setTile(tileX,tileY,20,-1)
  Drawing.drawImage(Draft.getDraft('bluepickle.plugin.meme.lights'):getFrame(1))
  Drawing.reset()
end

function script:event(x,y,level,event)
  if event == Script.EVENT_REMOVE and Tile.getBuildingDraft(x,y):getId() == buildingDraft:getId() and song then
    song.stop()
    bx, by = nil
    song = nil
  end
end

function script:nextDay()
  if City.countBuildings(buildingDraft) > 0 then
    bx, by = City.getBuilding(1, buildingDraft)
    if song then
      song.setPosition(bx, by)
    end
  end

  if bx and not song then
    song = City.playSound(songDraft, bx, by, 0.5, true)
  elseif song and not true then
    song.stop()
    song = nil
  end
end
