-- Krassort
-- 
--
-- author: fruktor
-- www.eifok-team.de
-- 

Krassort = {};


function Krassort.prerequisitesPresent(specializations)
    return true;
end;

function Krassort:load(xmlFile)	
	
	self.setSidewallLeft = SpecializationUtil.callSpecializationsFunction("setSidewallLeft");
	self.setSidewallRight = SpecializationUtil.callSpecializationsFunction("setSidewallRight");
	
	self.sw = {};

	self.sw.l = {};
	self.sw.l.idx = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.sidewall.left#index"));
	self.sw.l.charset = getAnimCharacterSet(self.sw.l.idx);
	self.sw.l.clipIdx = getAnimClipIndex(self.sw.l.charset, getXMLString(xmlFile, "vehicle.sidewall.left#clip"));	
	assignAnimTrackClip(self.sw.l.charset, 0, self.sw.l.clipIdx);
	setAnimTrackLoopState(self.sw.l.charset, 0, false);
	self.sw.l.duration = getAnimClipDuration(self.sw.l.charset, self.sw.l.clipIdx);	
	self.sw.l.bOpen = false;
	self.sw.l.bIsOpen = false;
	self.sw.l.bIsClosed = true;
	self.sw.l.jntIdx = getXMLInt(xmlFile, "vehicle.sidewall.left#jointIndex");
	
	self.sw.r = {};
	self.sw.r.idx = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.sidewall.right#index"));
	self.sw.r.charset = getAnimCharacterSet(self.sw.r.idx);
	self.sw.r.clipIdx = getAnimClipIndex(self.sw.r.charset, getXMLString(xmlFile, "vehicle.sidewall.right#clip"));	
	assignAnimTrackClip(self.sw.r.charset, 0, self.sw.r.clipIdx);
	setAnimTrackLoopState(self.sw.r.charset, 0, false);
	self.sw.r.duration = getAnimClipDuration(self.sw.r.charset, self.sw.r.clipIdx);	
	self.sw.r.jntIdx = getXMLInt(xmlFile, "vehicle.sidewall.right#jointIndex");
	self.sw.r.bOpen = false;
	self.sw.r.bIsOpen = false;
	self.sw.r.bIsClosed = true;

	--###
	self.timeDetachEnd = 0;
	
	--###
	self.doReleaseBales = false;
	self.balesReleased = false;

end;

function Krassort:delete()
end;

function Krassort:readStream(streamId, connection)
	self.sw.l.bOpen = streamReadBool(streamId);
	self.sw.l.bIsOpen = streamReadBool(streamId);
	self.sw.l.bIsClosed = streamReadBool(streamId);
	self.sw.r.bOpen = streamReadBool(streamId);
	self.sw.r.bIsOpen = streamReadBool(streamId);
	self.sw.r.bIsClosed = streamReadBool(streamId);
	local tt = streamReadFloat32(streamId);
	local tt2 = streamReadFloat32(streamId);
	enableAnimTrack(self.sw.l.charset, 0);
	setAnimTrackTime(self.sw.l.charset, 0, tt, true);
	disableAnimTrack(self.sw.l.charset, 0);	
	enableAnimTrack(self.sw.r.charset, 0);
	setAnimTrackTime(self.sw.r.charset, 0, tt2, true);
	disableAnimTrack(self.sw.r.charset, 0);
end;

function Krassort:writeStream(streamId, connection)	
	streamWriteBool(streamId, self.sw.l.bOpen);
	streamWriteBool(streamId, self.sw.l.bIsOpen);
	streamWriteBool(streamId, self.sw.l.bIsClosed);
	streamWriteBool(streamId, self.sw.r.bOpen);
	streamWriteBool(streamId, self.sw.r.bIsOpen);
	streamWriteBool(streamId, self.sw.r.bIsClosed);
	local tt = getAnimTrackTime(self.sw.l.charset, 0);
	streamWriteFloat32(streamId, tt);
	local tt2 = getAnimTrackTime(self.sw.r.charset, 0);
	streamWriteFloat32(streamId, tt2);
end;

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

function Krassort:keyEvent(unicode, sym, modifier, isDown)

end;

function Krassort:update(dt)

	
	if Vehicle.debugRendering then

	end;	
	
	
	--###
	if self:getIsActive() then
		--if self:getIsActiveForInput() then
			if self.isClient and self:getIsActiveForInput(true) and not self:hasInputConflictWithSelection() then
				if InputBinding.hasEvent(InputBinding.KRASSORT_LEFT) then
					self:setSidewallLeft(not self.sw.l.bOpen);
				end
				if InputBinding.hasEvent(InputBinding.KRASSORT_RIGHT) then
					self:setSidewallRight(not self.sw.r.bOpen);
				end
			end
		--end
	end
	
	--### LEFT
	if self.sw.l.bOpen == true and self.sw.l.bIsOpen == false then
		self.sw.l.bIsClosed = false;
		self.sw.l.bIsOpen = false;
		setAnimTrackSpeedScale(self.sw.l.charset, 0, 1.0);
		enableAnimTrack(self.sw.l.charset, 0);
		if self.isServer then
			setJointFrame(self.componentJoints[self.sw.l.jntIdx].jointIndex, 0, self.componentJoints[self.sw.l.jntIdx].jointNode);
		end;
		local tt = getAnimTrackTime(self.sw.l.charset, 0);
		if tt >= self.sw.l.duration then
			setAnimTrackTime(self.sw.l.charset, 0, self.sw.l.duration, true);
			disableAnimTrack(self.sw.l.charset, 0);
			self.sw.l.bIsOpen = true;
		end
	end;
	
	if self.sw.l.bOpen == false and self.sw.l.bIsClosed == false then
		self.sw.l.bIsClosed = false;
		self.sw.l.bIsOpen = false;
		setAnimTrackSpeedScale(self.sw.l.charset, 0, -1.0);
		enableAnimTrack(self.sw.l.charset, 0);
		if self.isServer then
			setJointFrame(self.componentJoints[self.sw.l.jntIdx].jointIndex, 0, self.componentJoints[self.sw.l.jntIdx].jointNode);
		end
		local tt = getAnimTrackTime(self.sw.l.charset, 0);
		if tt <= 0 then
			setAnimTrackTime(self.sw.l.charset, 0, 0.0, true);
			disableAnimTrack(self.sw.l.charset, 0);
			self.sw.l.bIsClosed = true;
		end
	end;
	
	
	--### RIGHT
	if self.sw.r.bOpen == true and self.sw.r.bIsOpen == false then
		self.sw.r.bIsClosed = false;
		self.sw.r.bIsOpen = false;
		setAnimTrackSpeedScale(self.sw.r.charset, 0, 1.0);
		enableAnimTrack(self.sw.r.charset, 0);
		if self.isServer then
			setJointFrame(self.componentJoints[self.sw.r.jntIdx].jointIndex, 0, self.componentJoints[self.sw.r.jntIdx].jointNode);
		end
		local tt = getAnimTrackTime(self.sw.r.charset, 0);
		if tt >= self.sw.r.duration then
			setAnimTrackTime(self.sw.r.charset, 0, self.sw.r.duration, true);
			disableAnimTrack(self.sw.r.charset, 0);
			self.sw.r.bIsOpen = true;
		end
	end;
	
	if self.sw.r.bOpen == false and self.sw.r.bIsClosed == false then
		self.sw.r.bIsClosed = false;
		self.sw.r.bIsOpen = false;
		setAnimTrackSpeedScale(self.sw.r.charset, 0, -1.0);
		enableAnimTrack(self.sw.r.charset, 0);
		if self.isServer then
			setJointFrame(self.componentJoints[self.sw.r.jntIdx].jointIndex, 0, self.componentJoints[self.sw.r.jntIdx].jointNode);
		end
		local tt = getAnimTrackTime(self.sw.r.charset, 0);
		if tt <= 0 then
			setAnimTrackTime(self.sw.r.charset, 0, 0.0, true);
			disableAnimTrack(self.sw.r.charset, 0);
			self.sw.r.bIsClosed = true;
		end
	end;	
	
	--#
	if self.sw.r.bIsClosed == false or self.sw.l.bIsClosed == false then
		self.doReleaseBales = true;
	else
		self.doReleaseBales = false;
	end
	
	--#
	--# dis-/enable automatic attaching
	if self.isServer then
		if self.doReleaseBales == true then 		
			
			for object,i in pairs(self.dynamicMountedObjects) do
				if object ~= nil then
					self:removeDynamicMountedObject(object, false);
					object:unmountDynamic();
					setCenterOfMass( object.nodeId, 0,0,0 );
				end;
			end			
			
		else 
			
			for object,_ in pairs(self.pendingDynamicMountObjects) do
				if self.dynamicMountedObjects[object] == nil then
					
					local cx,cy,cz = getWorldTranslation(self.components[1].node);
					local x,y,z = worldToLocal( object.nodeId, cx,cy,cz );
					setCenterOfMass( object.nodeId, x,y,z );
					
					if object:mountDynamic(self, self.dynamicMountAttacherTrigger.rootNode, self.dynamicMountAttacherTrigger.jointNode, false, self.dynamicMountAttacherTrigger.forceLimitScale) then
						self:addDynamicMountedObject(object);
					end				
				end
			end;
			
		end		
	end
	
	--# 
    if self.isServer then
		if self.doReleaseBales == true then
			-- overwrite bale time every frame -> DynMountAttacher does not attach, we do it here @ few lines above
			for object,_ in pairs(self.pendingDynamicMountObjects) do
				object.lastMoveTime = g_currentMission.time;
			end;
		end;
	end;
	
	--#
	if self.doReleaseBales == false then
		if self.downForce ~= 0 and self.isServer then
		
			local c = 0;
			for i,j in pairs(self.dynamicMountedObjects) do
				if i ~= nil then
					c = c + 1;
				end;
			end;
			local p = 1.0 * c / 32;
			--print("p="..p);
			
			local worldX,worldY,worldZ = localDirectionToWorld(self.components[1].node, 0, -self.downForce*p*dt/1000, 0);
			addForce(self.components[1].node, worldX, worldY, worldZ, 0, 0, 0, true);
		end;	
	end;
	

end;


function Krassort:updateTick(dt)

	if self.time < self.timeDetachEnd then
		Cylindered.updateMovingPart(self, self.movingParts[1]);
	end
				
end;

function Krassort:draw()
	g_currentMission:addHelpButtonText( g_i18n:getText("KRASSORT_LEFT_TEXT"), InputBinding.KRASSORT_LEFT );	
	g_currentMission:addHelpButtonText( g_i18n:getText("KRASSORT_RIGHT_TEXT"), InputBinding.KRASSORT_RIGHT );	
end;

function Krassort:loadFromAttributesAndNodes(xmlFile, key, resetVehicles)	
	local state1 = getXMLBool(xmlFile, key.."#SideLOpen");
	local state2 = getXMLBool(xmlFile, key.."#SideROpen");
	local tt1 = getXMLFloat(xmlFile, key.."#SideLTime");
	local tt2 = getXMLFloat(xmlFile, key.."#SideRTime");
	self.sw.l.bIsOpen = false;
	self.sw.l.bIsClosed = false;	
	self.sw.r.bIsOpen = false;
	self.sw.r.bIsClosed = false;
	enableAnimTrack(self.sw.l.charset, 0);
	setAnimTrackTime(self.sw.l.charset, 0, tt1, true);
	disableAnimTrack(self.sw.l.charset, 0);	
	enableAnimTrack(self.sw.r.charset, 0);
	setAnimTrackTime(self.sw.r.charset, 0, tt2, true);
	disableAnimTrack(self.sw.r.charset, 0);	
	self.sw.l.bOpen = state1; 
	self.sw.r.bOpen = state2; 
    return BaseMission.VEHICLE_LOAD_OK;
end;

function Krassort:getSaveAttributesAndNodes(nodeIdent)
	local tt = getAnimTrackTime(self.sw.l.charset, 0);
	local tt2 = getAnimTrackTime(self.sw.r.charset, 0);
    local attributes = 'SideLOpen="'.. tostring(self.sw.l.bOpen) .. '"';
	attributes = attributes .. ' SideROpen="'.. tostring(self.sw.r.bOpen) .. '"';
	attributes = attributes .. ' SideLTime="'.. tostring(tt) .. '"';
	attributes = attributes .. ' SideRTime="'.. tostring(tt2) .. '"';
    return attributes, nil;
end;

function Krassort:onAttach(attacherVehicle)
	setJointRotationLimit(self.componentJoints[2].jointIndex, 0, true, Utils.degToRad(-65), Utils.degToRad(65));
end;

function Krassort:onDetach()
	setJointRotationLimit(self.componentJoints[2].jointIndex, 0, true, Utils.degToRad(-1), Utils.degToRad(1));
	self.timeDetachEnd = self.time + 1500;
end;


--###
function Krassort:setSidewallLeft(state, noEventSend)	
	SetSidewallLeftEvent.sendEvent(self, state, noEventSend);
	self.sw.l.bOpen = state;	
end;

function Krassort:setSidewallRight(state, noEventSend)	
	SetSidewallRightEvent.sendEvent(self, state, noEventSend);
	self.sw.r.bOpen = state;	
end;
