#include <Urho3D/Core/Context.h>
#include <Urho3D/Scene/Node.h>
#include <Urho3D/Scene/Scene.h>
#include <Urho3D/Graphics/Material.h>
#include <Urho3D/Graphics/StaticModel.h>
#include <Urho3D/Scene/ValueAnimation.h>
#include <Urho3D/Physics/PhysicsEvents.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Physics/RigidBody.h>

#include "Common.h"
#include "Remover.h"

namespace {
    constexpr auto E_FDS_REMOVE = "fds-remove";
}

Remover::Remover(Context* context) :
    LogicComponent(context)
{
}

void Remover::RegisterObject(Context* context)
{
    context->RegisterFactory<Remover>();
}

void Remover::Start()
{
    // Component has been inserted into its scene node. Subscribe to events now
    SubscribeToEvent(GetNode(), E_NODECOLLISION, URHO3D_HANDLER(Remover, HandleNodeCollision));
}


void Remover::HandleNodeCollision(StringHash, VariantMap& eventData) {
    using namespace NodeCollision;

    auto otherNode = static_cast<Node*>(eventData[P_OTHERNODE].GetPtr());
    if (otherNode->HasTag("player")) {
        return;
    }

    UnsubscribeFromEvent(GetNode(), E_NODECOLLISION);

    auto node = GetNode();

    auto cache = GetSubsystem<ResourceCache>();
    auto boxObject = node->GetComponent<StaticModel>();
    boxObject->SetMaterial(cache->GetResource<Material>("fds/TofuMaterial.xml"));

    auto constexpr REMOVE_TIME = 4.0f;
    auto constexpr SHRINK_TIME = REMOVE_TIME + 0.25f;
    ValueAnimation* anim{ new ValueAnimation{ context_ } };
    auto scale = node->GetScale();
    anim->SetKeyFrame(0.0f, scale);
    anim->SetKeyFrame(REMOVE_TIME, scale);
    anim->SetKeyFrame(SHRINK_TIME, Vector3::ZERO);
    anim->SetEventFrame(SHRINK_TIME, E_FDS_REMOVE);
    node->SetAttributeAnimation("Scale", anim, WM_ONCE);
    SubscribeToEvent(node, E_FDS_REMOVE, URHO3D_HANDLER(Remover, HandleShrinkEnd));
}

void Remover::HandleShrinkEnd(StringHash, VariantMap&) {
    GetNode()->Remove();
}
