--# CardDeal
-- Deals the deck out to the four shelves, thirteen cards each, one at a time.
-- Only ever runs after the prompt below is tapped.

Deal = class()

function Deal:init(cardTable)
  self.cardTable = cardTable
  self.state = nil -- nil or "dealing"
  self.timer = 0
  self.interval = 0.01
  self.queue = {}
end

function Deal:isActive()
  return self.state ~= nil
end

function Deal:begin()
  if self:isActive() then return end
  local shuffled = {}
  for _, card in ipairs(self.cardTable.cards) do table.insert(shuffled, card) end
  for i = #shuffled, 2, -1 do
    local j = math.random(i)
    shuffled[i], shuffled[j] = shuffled[j], shuffled[i]
  end
  local shelves = self.cardTable.shelves.all
  self.queue = {}
  for i, card in ipairs(shuffled) do
    local shelf = shelves[((i - 1) % #shelves) + 1]
    table.insert(self.queue, {card = card, shelf = shelf})
  end
  self.state = "dealing"
  self.timer = 0
end

function Deal:update()
  if self.state ~= "dealing" then return end
  self.timer = self.timer + DeltaTime
  if #self.queue == 0 then
    self.state = nil
  elseif self.timer >= self.interval then
    self.timer = 0
    self:dealNext()
  end
end

function Deal:dealNext()
  local entry = table.remove(self.queue, 1)
  if entry then entry.shelf:accept({entry.card}) end
end

-- Shows "tap deck" / "to deal" over the gathered pile right after a shuffle
-- settles. Tapping the deck starts the deal; any other touch just dismisses
-- the prompt, handled by CardTouch before its normal touch handling runs.

DealPrompt = class()

function DealPrompt:init(cardTable)
  self.cardTable = cardTable
  self.active = false
end

function DealPrompt:show()
  self.active = true
end

function DealPrompt:hide()
  self.active = false
end

function DealPrompt:deckCenter()
  return vec2(WIDTH / 2, HEIGHT / 2)
end

function DealPrompt:touchIsOnDeck(touch)
  local center = self:deckCenter()
  local halfW = self.cardTable:cardWidth() * 0.5
  local halfH = self.cardTable:cardHeight() * 0.5
  return math.abs(touch.pos.x - center.x) <= halfW and math.abs(touch.pos.y - center.y) <= halfH
end

function DealPrompt:draw()
  if not self.active then return end
  local center = self:deckCenter()
  local halfH = self.cardTable:cardHeight() * 0.5
  local margin = self.cardTable:cardHeight() * 0.3
  pushStyle()
  fill(255)
  font("HelveticaNeue-Bold")
  fontSize(self.cardTable:cardWidth() * 0.22)
  text("tap deck", center.x, center.y + halfH + margin)
  local toDealY = center.y - halfH - margin
  text("to deal", center.x, toDealY)
  local _, lineHeight = textSize("to deal")
  fontSize(self.cardTable:cardWidth() * 0.175)
  fill(255, 210)
  textAlign(CENTER)
  text("tap anywhere else\nto cancel", center.x, toDealY - lineHeight * 1.9)
  popStyle()
end
