// Copyright (c) 2022 Dominic Masters
// 
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT

#include "PokerPlayerDisplay.hpp"
#include "game/DawnGame.hpp"

using namespace Dawn;

PokerPlayerDisplay::PokerPlayerDisplay(UICanvas *canvas) :
  UIEmpty(canvas),
  labelName(canvas),
  labelChips(canvas),
  borderInner(canvas),
  border(canvas),
  animChips(&animChipsValue)
{
  this->font = getGame()->assetManager.get<TrueTypeAsset>("truetype_ark");

  // Border
  this->addChild(&this->border);
  PokerGameBorder::apply(&this->border);
  this->border.setTransform(
    UI_COMPONENT_ALIGN_STRETCH, UI_COMPONENT_ALIGN_STRETCH,
    glm::vec4(0, 0, 0, 0),
    0.0f
  );

  // Border Inner
  this->addChild(&this->borderInner);
  this->borderInner.setTransform(
    UI_COMPONENT_ALIGN_STRETCH, UI_COMPONENT_ALIGN_STRETCH,
    glm::vec4(this->border.getBorderSize(), this->border.getBorderSize()),
    0.0f
  );

  // Player Name
  this->borderInner.addChild(&this->labelName); 
  this->labelName.setText("undefined");
  this->labelName.setFont(&this->font->font);
  this->labelName.setFontSize(40);
  this->labelName.setTransform(
    UI_COMPONENT_ALIGN_START, UI_COMPONENT_ALIGN_START, 
    glm::vec4(0, 0, 0, 0),
    0.0f
  );

  // Chips label
  this->borderInner.addChild(&this->labelChips);
  this->labelChips.setFont(&this->font->font);
  this->labelChips.setFontSize(40);
  this->labelChips.setTransform(
    UI_COMPONENT_ALIGN_START, UI_COMPONENT_ALIGN_START, 
    glm::vec4(0, this->labelName.getContentHeight(), 0, 0),
    0.0f
  );

  // Anim
  this->animChips.easing = &easeOutQuart;

  // Events
  getScene()->eventSceneUnpausedUpdate.addListener(this, &PokerPlayerDisplay::onSceneUpdate);
}

void PokerPlayerDisplay::setPlayer(PokerPlayer *player) {
  assertNull(this->player);
  this->player = player;

  player->eventChipsChanged.addListener(this, &PokerPlayerDisplay::onPlayerChipsChanged);

  this->labelName.setText("undefined");
  this->animChips.clear();
  this->animChips.restart();
  this->animChipsValue = player->chips;

  this->updatePositions();
}

void PokerPlayerDisplay::onSceneUpdate() {
  this->animChips.tick(getGame()->timeManager.delta);

  // std::stringstream stream;
  // stream.precision(0);
  // stream << "$";
  // stream << this->animChipsValue;
  this->labelChips.setText("undefined");
}

void PokerPlayerDisplay::onPlayerChipsChanged() {
  std::cout << "Chips" << player->chips << std::endl;

  this->animChips.clear();
  this->animChips.addKeyframe(0.0f, this->animChipsValue);
  this->animChips.addKeyframe(1.0f, this->player->chips);
  this->animChips.restart();
}

PokerPlayerDisplay::~PokerPlayerDisplay() {
  this->canvas->getScene()->eventSceneUnpausedUpdate.removeListener(this, &PokerPlayerDisplay::onSceneUpdate);
}