#include "BlockAnimation.h"

BlockAnimation::BlockAnimation(
    Block* block, Framework::SkeletonAnimation* animation)
    : ReferenceCounter(),
      block(block),
      animation(animation)
{}

BlockAnimation::~BlockAnimation() {
    block->release();
    if(animation) animation->release();
}

void BlockAnimation::appendAnimation(int boneId,
    double time,
    Framework::Vec3<float> pos,
    Framework::Vec3<float> rot)
{
    BoneAnimation* ba = animation->zAnimation(boneId);
    if (ba)
    {
        ba->addKeyFrame(ba->getMaxTime() + time, pos, rot);
    }
    else
    {
        Bone* bone = block->zSkeleton()->zBone(boneId);
        animation->addAnimation(
            boneId, bone->getPosition(), bone->getRotation());
        animation->addKeyFrame(boneId, time, pos, rot);
    }
}

bool BlockAnimation::tick(double time) {
    if (animation)
    {
        animation->tick(time);
        animation->apply(block->zSkeleton());
        if (animation->isFinished())
        {
            animation->release();
            animation = 0;
        }
        return 1;
    }
    return 0;
}

bool BlockAnimation::isFinished() const {
    return animation == 0;
}

Block* BlockAnimation::zBlock() const {
    return block;
}