// Copyright (C) 2021 - Sebastien Alaiwan
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.

// Bonus entity

#include <cmath> // sin

#include "base/scene.h"
#include "base/util.h"

#include "gameplay/collision_groups.h"
#include "gameplay/entity.h"
#include "gameplay/entity_factory.h"
#include "gameplay/models.h"
#include "gameplay/player.h"
#include "gameplay/sounds.h"

namespace
{
struct Trinket : Entity
{
  Trinket(IEntityConfig*)
  {
    size = UnitSize;
    Body::onCollision = [this] (Body* other) { onCollide(other); };

    collidesWith = CG_SOLIDPLAYER;
    collisionGroup = CG_BONUS;
  }

  void enter() override
  {
    auto var = game->getVariable(id);

    // already picked up?
    if(var->get())
    {
      Body::onCollision = [] (Body*) {};
      dead = true;
    }
  }

  void addActors(std::vector<SpriteActor>& actors) const override
  {
    auto s = sin(time * 0.1);
    auto r = SpriteActor { pos + UnitSize / 2, MDL_BONUS };
    r.scale = UnitSize;
    r.ratio = std::max(s, 0.0);
    r.action = 0;

    actors.push_back(r);
  }

  void tick() override
  {
    ++time;
  }

  void onCollide(Body* other)
  {
    if(auto player = dynamic_cast<Playerable*>(other))
    {
      player->getPlayer()->addTrinket();
      game->playSound(SND_BONUS);
      dead = true;

      auto var = game->getVariable(id);
      var->set(1);

      Body::onCollision = [] (Body*) {};
    }
  }

  static constexpr uint32_t flags = EntityFlag_ShowOnMinimap_O | EntityFlag_Persist;

  int time = 0;
};

DECLARE_ENTITY("trinket", Trinket);
}

