--# Card

Card = class()
Card.allSuits = {"spades", "hearts", "diamonds", "clubs"}
Card.borderColor = color(48, 48, 52)
Card.borderWidth = 1

-- real cards are 64mm by 89mm, scaled here against the screen's diagonal so
-- they come out the same size in either orientation
function Card:init(rank, suit, startingPosition)
  self.rank = rank or 1
  self.suit = suit or "spades"
  local diagonal = math.sqrt((WIDTH * WIDTH) + (HEIGHT * HEIGHT))
  self.width = diagonal * 0.0853333
  self.height = diagonal * 0.1196666
  self.body = lab.make:box(startingPosition or vec2(0, 0), self.width, self.height)
  self.body.angle = 0
  self.body.linearDamping = 4
  self.body.angularDamping = 5
  self.body.categories = {2}
  self.body.mask = {1}
  self.body.owningClass = "card"
  self.body.owner = self
  self.body.shortName = self:shortName()
  self.back = asset.cardBackMonkey
  self.face = asset[self:shortName()..".png"]
  self.showing = self.back
  local borderSize = self.width / 10
  self.borderScale = vec2(self.width + borderSize, self.height + borderSize)
  -- the hairline sits just outside the card, so it never covers the artwork
  self.edgeScale = vec2(self.width + Card.borderWidth * 2, self.height + Card.borderWidth * 2)
end

function Card:draw()
  if not self.body then return end
  pushStyle()
  pushMatrix()
  resetMatrix()
  translate(self.body.x, self.body.y)
  rotate(self.body.angle)
  if self.body.isPickerUpper and not cardTable.shelves.shownShelf then
    self:drawPickerUpperBorder()
  end
  self:drawEdge()
  sprite(self.showing, 0, 0, self.width, self.height)
  popMatrix()
  popStyle()
end

-- a slightly larger copy of the same sprite, tinted flat dark, drawn behind
-- the card. using the card's own image keeps the rounded corners exact.
function Card:drawEdge()
  pushStyle()
  tint(Card.borderColor)
  sprite(self.showing, 0, 0, self.edgeScale.x, self.edgeScale.y)
  popStyle()
end

function Card:drawPickerUpperBorder()
  pushStyle()
  tint(204, 0, 255, 203)
  sprite(self.showing, 0, 0, self.borderScale.x, self.borderScale.y)
  popStyle()
end

function Card:shortName()
  local suitInitial
  if self.suit == "spades" then
    suitInitial = "S"
  elseif self.suit == "hearts" then
    suitInitial = "H"
  elseif self.suit == "diamonds" then
    suitInitial = "D"
  elseif self.suit == "clubs" then
    suitInitial = "C"
  end
  return suitInitial..self.rank
end

function Card:flip()
  if self.showing == self.back then
    self.showing = self.face
  else
    self.showing = self.back
  end
end

function Card:faceDown()
  self.showing = self.back
end

function Card:faceUp()
  self.showing = self.face
end
