local BaseObject = require "app/bf/unity/base_object"
local MeshSpineObject = class("SpineObject", BaseObject)

function MeshSpineObject:ctor()
end

function MeshSpineObject:initSkeletonDataAsset(dataAsset)
    local skeletonAnimation = self:getSkeletonAnimation()
    skeletonAnimation.skeletonDataAsset = dataAsset
    skeletonAnimation:Initialize(false)
end

function MeshSpineObject:getSkeletonAnimation()
    if not self.skeletonAnimation then
        self.skeletonAnimation = self:getComponent(GConst.TYPEOF_UNITY_CLASS.SKELETON_ANIMATION)
    end
    return self.skeletonAnimation
end

function MeshSpineObject:getAnimationState()
    self:getSkeletonAnimation()
    if not self.animationState then
        self.animationState = self.skeletonAnimation.AnimationState
    end
    return self.animationState
end

function MeshSpineObject:playAnim(animName, loop, forceRefresh)
    self:getAnimationState()
    if self.animationState then
        local trackEntry = self.animationState:SetAnimation(0, animName, loop)
        if forceRefresh then
            self.skeletonAnimation:Update(0)
        end
        return trackEntry
    end
end

function MeshSpineObject:setTimeScale(timeScale)
    if self.skeletonAnimation then
        self.skeletonAnimation.timeScale = timeScale
    end
end

function MeshSpineObject:setIsLoop(isLoop)
    if self.skeletonAnimation then
        self.skeletonAnimation.loop = isLoop
    end
end

function MeshSpineObject:addAnimationCompleteCallback(callback)
    if self._animationStateCompleteCallback then
        return
    end
    self._animationStateCompleteCallback = function(entry)
        callback(entry.Animation.Name)
    end
    local state = self:getAnimationState()
    state:Complete("+", self._animationStateCompleteCallback)
end

function MeshSpineObject:removeAnimationCompleteCallback()
	if self._animationStateCompleteCallback then
        local state = self:getAnimationState()
        state:Complete("-", self._animationStateCompleteCallback)
        self._animationStateCompleteCallback = nil
    end
end

function MeshSpineObject:onDestroy()
    self:removeAnimationCompleteCallback()
    BaseObject.onDestroy(self)
    self.skeletonAnimation = nil
    self.animationState = nil
end

return MeshSpineObject