--
-- SupportFrame
--
-- @author  Manuel Leithner
-- @date  01/10/19
--
-- Copyright (C) GIANTS Software GmbH, Confidential, All Rights Reserved.

local modName = g_currentModName

local function getSpecTable(self)
    return self["spec_"..modName..".supportFrame"]
end

-- @category Specializations
SupportFrame = {}

---Checks if all prerequisite specializations are loaded
-- @param table specializations specializations
-- @return boolean hasPrerequisite true if all prerequisite specializations are loaded
-- @includeCode
function SupportFrame.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(AnimatedVehicle, specializations)
end

---
-- @includeCode
function SupportFrame.registerFunctions(vehicleType)
    SpecializationUtil.registerFunction(vehicleType, "setSupportFrameValue", SupportFrame.setSupportFrameValue)
    SpecializationUtil.registerFunction(vehicleType, "loadSupportFrame", SupportFrame.loadSupportFrame)
end

---
-- @includeCode
function SupportFrame.registerEventListeners(vehicleType)
    SpecializationUtil.registerEventListener(vehicleType, "onLoad", SupportFrame)
    SpecializationUtil.registerEventListener(vehicleType, "onPostDetach", SupportFrame)
end

function SupportFrame:onLoad(savegame)
    local spec = getSpecTable(self)

    spec.supportFrames = {}

    local i = 0
    while true do
        local key = string.format("vehicle.supportFrame.frame(%d)", i)
        if not hasXMLProperty(self.xmlFile, key) then
            break
        end

        local frame = {}

        if self:loadSupportFrame(self.xmlFile, key, frame) then
            table.insert(spec.supportFrames, frame)
        end

        i = i + 1
    end
end

function SupportFrame:onPostDetach()
    local spec = getSpecTable(self)
    for _, supportFrame in ipairs(spec.supportFrames) do
        local animationName = supportFrame.animationName
        self:setAnimationTime(animationName, 0, true)
    end
end

function SupportFrame:setSupportFrameValue(frameIndex, value)
    local spec = getSpecTable(self)
    local frame = spec.supportFrames[frameIndex]
    if frame ~= nil then
        local animationName = frame.animationName
        self:setAnimationTime(animationName, value, true)
    end
end

function SupportFrame:loadSupportFrame(xmlFile, key, frame)

    local animName = getXMLString(xmlFile, key.."#animName")
    if animName ~= nil then
        frame.animationName = animName

        return true
    end

    return false
end