--
-- Bolko Z-643
-- author: Burner
-- 

source("dataS/scripts/vehicles/specializations/SetTurnedOnEvent.lua");
Bolko = {};

function Bolko.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Trailer, specializations);
end;

function Bolko:load(xmlFile)
	self.setTransport = SpecializationUtil.callSpecializationsFunction("setTransport");	
    self.setIsTurnedOn = SpecializationUtil.callSpecializationsFunction("setIsTurnedOn");
    self.fillScale = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.fillScale#value"), 1);
    self.wasToFast = false;
    self.isTurnedOn = false;
	self.currentFruitType = FruitUtil.FRUITTYPE_UNKNOWN;
	
	self.lastArea = 0;
	self.lastAreaBiggerZero = self.lastArea > 0;

    self.BolkoGroundFlag = self:getNextDirtyFlag();

	self.beben = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.beben#index"));	
	self.parobek = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.parobek#index"));
	self.walek = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.walek#index"));
	self.talerz = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.talerz#index"));

	self.liscie = {};
    local i = 0;
    while true do
        local namei = string.format("vehicle.liscie.liscie(%d)", i);
		local nodei = Utils.indexToObject(self.components, getXMLString(xmlFile, namei .. "#index"));
		if nodei == nil then
			break;
		end;
		StaticParticleSystem.loadParticleSystem(xmlFile, self.liscie, namei, nodei, false, nil, self.baseDirectory);
		Utils.setEmittingState(self.liscie,false)
		self.particleSystemdisableTime = 0;
		i = i +1;		
    end;
	self.kurz = {};
    local i = 0;
    while true do
        local namei = string.format("vehicle.kurz.kurz(%d)", i);
		local nodei = Utils.indexToObject(self.components, getXMLString(xmlFile, namei .. "#index"));
		if nodei == nil then
			break;
		end; 
		StaticParticleSystem.loadParticleSystem(xmlFile, self.kurz, namei, nodei, false, nil, self.baseDirectory);
		Utils.setEmittingState(self.kurz,false)
		self.particleSystemdisableTime = 0;
		i = i +1;		
    end;
	
	self.TransportAnimation = getXMLString(xmlFile, "vehicle.Transport#animationName");
	self.Transport = true;
	
    self.UVScrollParts = {};
    local i = 0;
    while true do
        local key = string.format("vehicle.UVScrollParts.UVScrollPart(%d)", i);
        if not hasXMLProperty(xmlFile, key) then
            break;
        end;
        local node = Utils.indexToObject(self.components, getXMLString(xmlFile, key.."#index"));
        local speed = Utils.getVectorNFromString(getXMLString(xmlFile, key.."#speed"), 2);
        if node ~= nil and speed then
            table.insert(self.UVScrollParts, {node=node, speed=speed});
        end;
        i = i +1;
    end;
end;

function Bolko:delete()
end;

function Bolko:readStream(streamId, connection)
    local turnedOn = streamReadBool(streamId);
    self:setIsTurnedOn(turnedOn, true);
    local fillLevel = streamReadInt32(streamId);
	self:setTransport(streamReadBool(streamId), true);
	self.lastAreaBiggerZero = streamReadBool(streamId);
end;

function Bolko:writeStream(streamId, connection)
    streamWriteBool(streamId, self.isTurnedOn);
    streamWriteInt32(streamId, self.fillLevel);
	streamWriteBool(streamId, self.Transport);
	streamWriteBool(streamId, self.lastAreaBiggerZero);
end;

function Bolko:readUpdateStream(streamId, timestamp, connection)
	if connection:getIsServer() then
		self.lastAreaBiggerZero = streamReadBool(streamId);
	end;
end;

function Bolko:writeUpdateStream(streamId, connection, dirtyMask)
	if not connection:getIsServer() then
		streamWriteBool(streamId, self.lastAreaBiggerZero);
	end;
end;

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

function Bolko:keyEvent(unicode, sym, modifier, isDown)
end;

function Bolko:update(dt)
    if self:getIsActiveForInput() then
        if InputBinding.hasEvent(InputBinding.IMPLEMENT_EXTRA) then
            self:setIsTurnedOn(not self.isTurnedOn);
        end;
		if InputBinding.hasEvent(InputBinding.Bolko_ToggleTransport) then
			self:setTransport(not self.Transport);
		end;
    end;
end;

function Bolko:updateTick(dt)
	if self.attacherVehicle ~= nil then
		for k, implement in pairs(self.attacherVehicle.attachedImplements) do
			local jointDesc = self.attacherVehicle.attacherJoints[implement.jointDescIndex];
			if k == self.attacherVehicle.selectedImplement  then
				setJointFrame(jointDesc.jointIndex, 1, self.attacherJoint.node);
			end;
		end;
	end;
    self.wasToFast = false;
    self.lastArea = 0;
    if self:getIsActive() then
		if self.isTurnedOn then
			rotate(self.beben, dt*0.015, 0, 0 );
			rotate(self.walek, 0, 0, 0.8);
			rotate(self.talerz, dt*0.01, 0, 0 );
		end;
        if self.isTurnedOn and self.capacity > self.fillLevel then
			Utils.setEmittingState(self.liscie, self.lastAreaBiggerZero);
			Utils.setEmittingState(self.kurz, self.lastAreaBiggerZero);
            local toFast = self:doCheckSpeedLimit() and self.attacherVehicle.lastSpeed*3600 > 29;
            if self.isServer then
                if not toFast then
                    local cuttingAreasSend = {};
                    for k, cuttingArea in pairs(self.cuttingAreas) do
                        if self:getIsAreaActive(cuttingArea) then
                            local x,y,z = getWorldTranslation(cuttingArea.start);
                            local x1,y1,z1 = getWorldTranslation(cuttingArea.width);
                            local x2,y2,z2 = getWorldTranslation(cuttingArea.height);
                            table.insert(cuttingAreasSend, {x,z,x1,z1,x2,z2});
                        end;
                    end;
                    if (table.getn(cuttingAreasSend) > 0) then
						local lastArea, fillType = BolkoAreaEvent.runLocally(cuttingAreasSend, self.fillTypes, self.currentFillType);
						self.lastArea = lastArea;
						self.lastAreaBiggerZero = (self.lastArea > 0);
                        if lastArea > 0 then
							self.currentFruitType = FruitUtil.fillTypeToFruitType[fillType];
                            local pixelToSqm = g_currentMission:getFruitPixelsToSqm(); -- 4096px are mapped to 2048m
							literPerSqm = FruitUtil.fruitIndexToDesc[self.currentFruitType].literPerSqm;
                            local sqm = lastArea *pixelToSqm;
                            local deltaLevel = sqm*literPerSqm * self.fillScale;
                            self:setFillLevel(self.fillLevel+deltaLevel, fillType);
							g_server:broadcastEvent(BolkoAreaEvent:new(cuttingAreasSend, fillType));
                        end;
                    end;
                end;
            end;
            self.wasToFast = toFast;
		else
			Utils.setEmittingState(self.liscie, false);
			Utils.setEmittingState(self.kurz, false);
        end;
    end;
	setVisibility(self.parobek, not self.Transport);
end;

function Bolko:draw()
    if self.wasToFast then
        g_currentMission:addWarning(g_i18n:getText("Dont_drive_to_fast") .. "\n" .. string.format(g_i18n:getText("Cruise_control_levelN"), "2", InputBinding.getKeyNamesOfDigitalAction(InputBinding.SPEED_LEVEL2)), 0.07+0.022, 0.019+0.029);
    end;
    if self.isTurnedOn then
        g_currentMission:addHelpButtonText(string.format(g_i18n:getText("turn_off_OBJECT"), self.typeDesc), InputBinding.IMPLEMENT_EXTRA);
    else
        g_currentMission:addHelpButtonText(string.format(g_i18n:getText("turn_on_OBJECT"), self.typeDesc), InputBinding.IMPLEMENT_EXTRA);
    end;
	if self.Transport then
        g_currentMission:addHelpButtonText(string.format(g_i18n:getText("TRANSPORT_OFF"), self.typeDesc), InputBinding.Bolko_ToggleTransport);
    else
		g_currentMission:addHelpButtonText(string.format(g_i18n:getText("TRANSPORT_ON"), self.typeDesc), InputBinding.Bolko_ToggleTransport);
    end;
end;

function Bolko:onDetach()
	Utils.setEmittingState(self.liscie, false);
	Utils.setEmittingState(self.kurz, false);
    if self.deactivateOnDetach then
        Bolko.onDeactivate(self);
    else
    end;
    for _, part in pairs(self.UVScrollParts) do
        setShaderParameter(part.node, "uvScrollSpeed", 0, 0, 0, 0, false);
    end;
end;

function Bolko:onLeave()
	Utils.setEmittingState(self.liscie, false);
	Utils.setEmittingState(self.kurz, false);
    if self.deactivateOnLeave then
        Bolko.onDeactivate(self);
    else
    end;
    for _, part in pairs(self.UVScrollParts) do
        setShaderParameter(part.node, "uvScrollSpeed", 0, 0, 0, 0, false);
    end;
end;

function Bolko:onDeactivate()
	Utils.setEmittingState(self.liscie, false);
	Utils.setEmittingState(self.kurz, false);
    self.isTurnedOn = false;
    for _, part in pairs(self.UVScrollParts) do
        setShaderParameter(part.node, "uvScrollSpeed", 0, 0, 0, 0, false);
    end;
end;

function Bolko:setIsTurnedOn(turnedOn, noEventSend)
    SetTurnedOnEvent.sendEvent(self, turnedOn, noEventSend)
    self.isTurnedOn = turnedOn;
	for _, part in pairs(self.UVScrollParts) do
		if self.isTurnedOn then
			setShaderParameter(part.node, "uvScrollSpeed", part.speed[1], part.speed[2], 0, 0, false);
		else
			setShaderParameter(part.node, "uvScrollSpeed", 0, 0, 0, 0, false);
		end;
    end;
end;

function Bolko:setTransport(isTransport,noEventSend)
	SetTransportEvent.sendEvent(self, isTransport, noEventSend);
	-- Play transport animation --
	if isTransport then
		if self.TransportAnimation ~= nil and self.playAnimation ~= nil then
			self:playAnimation(self.TransportAnimation, -1, nil, true);
			self.Transport = true;
		end;
	else
		if self.TransportAnimation ~= nil and self.playAnimation ~= nil then
			self:playAnimation(self.TransportAnimation, 1, nil, true);
			self.Transport = false;
		end;
	end;
end;