--
-- KSK100A
-- 
--

KSK100 = {};

function KSK100.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Motorized, specializations);
end;

function KSK100:load(xmlFile)
	self.setGrainFlaps = SpecializationUtil.callSpecializationsFunction("setGrainFlaps");
	self.grainFlapsAnimation = getXMLString(xmlFile, "vehicle.grainFlaps#animationName");
	self.grainFlaps = true;
	
	self.rollNodes = {};
	
    local rollNode = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.roll#index"));
    if rollNode ~= nil then
        local speed = 0.003*3;
        table.insert(self.rollNodes, {node=rollNode, speed=speed});
    end;
    local i = 0;
    while true do
        local key = string.format("vehicle.rolls.roll(%d)", i);
        if not hasXMLProperty(xmlFile, key) then
            break;
        end;
        local rollNode = Utils.indexToObject(self.components, getXMLString(xmlFile, key.."#index"));
        local speed = Utils.getNoNil(getXMLFloat(xmlFile, key.."#speed"), 0.003);
        if rollNode ~= nil then
            table.insert(self.rollNodes, {node=rollNode, speed=speed});
        end;
        i = i + 1;
    end;
end;

function KSK100:readStream(streamId, connection)
	self:setGrainFlaps(streamReadBool(streamId), true);
end;

function KSK100:writeStream(streamId, connection)
	streamWriteBool(streamId, self.grainFlaps);
end;

function KSK100:delete()
end;

 
function KSK100:mouseEvent(posX, posY, isDown, isUp, button)
end;

function KSK100:keyEvent(unicode, sym, modifier, isDown)
end;
 
function KSK100:update(dt)
	if self:getIsActiveForSound() then
		if InputBinding.hasEvent(InputBinding.KSK100_TOGGLE_GRAIN_FLAP) then
			self:setGrainFlaps(not self.grainFlaps);
		end;
	end;
	--if self:getIsActive() then
		if self.isThreshing then
			for _, rollNode in pairs(self.rollNodes) do
				rotate(rollNode.node, -dt*rollNode.speed, 0, 0);
			end;
		end;
	--end;
end;

function KSK100:onLeave()
end;

function KSK100:draw()
	if self.grainFlaps then
		g_currentMission:addHelpButtonText(string.format(g_i18n:getText("KSK100_OpenGrainFlaps"), self.typeDesc), InputBinding.KSK100_TOGGLE_GRAIN_FLAP);
	else
		g_currentMission:addHelpButtonText(string.format(g_i18n:getText("KSK100_CloseGrainFlaps"), self.typeDesc), InputBinding.KSK100_TOGGLE_GRAIN_FLAP);
	end;
end;

function KSK100:setGrainFlaps(grainFlapsState,noEventSend)
	SetGrainFlapsEvent.sendEvent(self, grainFlapsState, noEventSend);
	if grainFlapsState then
		if self.grainFlapsAnimation ~= nil and self.playAnimation ~= nil then
			self:playAnimation(self.grainFlapsAnimation, -1, nil, true);
			self.grainFlaps = true;
		end;
	else
		if self.grainFlapsAnimation ~= nil and self.playAnimation ~= nil then
			self:playAnimation(self.grainFlapsAnimation, 1, nil, true);
			self.grainFlaps = false;
		end;
	end;
end;