--
-- HatchTipping
-- Class for trailers to fill sowers
--
-- @author  PeterJ  - euroDZN
-- @date  18/03/2013
--
-- http://eurodzn.wordpress.com/
--
-- Copyright (C) euroDZN, Confidential, All Rights Reserved.

HatchTipping = {}

function HatchTipping.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Trailer, specializations) and SpecializationUtil.hasSpecialization(GaluchoTipMode, specializations);
end;

function HatchTipping:load(xmlFile)

	self.setIsTurnedOn = SpecializationUtil.callSpecializationsFunction("setIsTurnedOn");
	self.getIsTurnedOnAllowed = HatchTipping.getIsTurnedOnAllowed;
	self.turnOnAnimation = getXMLString(xmlFile, "vehicle.hatchTipping#tipToFillaleAnimName");

	self.isTurnedOn = false;
	if self.hatchAnimIdx == 1 then
		self.hatchDischargeStartTime = self.dischargeStartTime1;
		self.hatchEndDichargeTime = self.dischargeEndTime1;
	elseif self.hatchAnimIdx == 2 then
		self.hatchDischargeStartTime = self.dischargeStartTime2;
		self.hatchEndDichargeTime = self.dischargeEndTime2;
	elseif self.hatchAnimIdx == 3 then
		self.hatchDischargeStartTime = self.dischargeStartTime3;
		self.hatchEndDichargeTime = self.dischargeEndTime3;
	end;
	
	self.animTurnOnSpeedScale = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.tipAnimation#speedScale"), 1);
	
	--- Trigger ---
	self.FillableTrigger = HatchTipping.FillableTrigger;
	self.FillableTriggers = {};
  
	local FillableTrigger = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.hatchTipping#fillableTrigger"));
	if FillableTrigger ~= nil then
		self.FillableTriggers[FillableTrigger] = {node=FillableTrigger};
	end;
	for _, FillableTrigger in pairs(self.FillableTriggers) do
		addTrigger(FillableTrigger.node, "FillableTrigger", self);
	end;
	self.fillAbleObjectInRange = nil;
	
	self.seedFillType = Fillable.FILLTYPE_SEEDS;
	self.potatoFillType = Fillable.FILLTYPE_POTATO;
	self.sugarBeetFillType = Fillable.FILLTYPE_SUGARBEET;

	--- Show fill level of machine in range ---
	self.hudFillLevelBasePosX = 0.01;
	self.hudFillLevelBasePosY = 0.0149;
	self.hudFillLevelBaseWidth = 0.2;
	self.hudFillLevelBaseHeight = 0.043;
	self.hudFillLevelBarWidth = 0.168;
	self.hudFillLevelOverlay = Overlay:new("hudFillLevelOverlay", "dataS2/menu/hud/vehicleHUD_barGold.png", self.hudFillLevelBasePosX + 0.0228, self.hudFillLevelBasePosY + 0.003, self.hudFillLevelBaseWidth - 0.03, self.hudFillLevelBaseHeight - 0.012);
	self.FillLevelBasePath = Utils.getFilename("textures/FillLevelBase.png", self.baseDirectory);
	self.hudFillLevelBase = Overlay:new("hudFillLevelBase", self.FillLevelBasePath, self.hudFillLevelBasePosX, self.hudFillLevelBasePosY, self.hudFillLevelBaseWidth, self.hudFillLevelBaseHeight);
	self.FillLevelFramePath = Utils.getFilename("textures/FillLevelFrame.png", self.baseDirectory);
	self.hudFillLevelFrame = Overlay:new("hudFillLevelFrame", self.FillLevelFramePath, self.hudFillLevelBasePosX, self.hudFillLevelBasePosY, self.hudFillLevelBaseWidth, self.hudFillLevelBaseHeight);

	--- fill sound ---
    if self.isClient then
        local fillingSound = getXMLString(xmlFile, "vehicle.fillSound#file");
        if fillingSound ~= nil and fillingSound ~= "" then
            fillingSound = Utils.getFilename(fillingSound, self.baseDirectory);
            self.fillingSound = createSample("fillingSound");
            self.fillingSoundEnabled = false;
            loadSample(self.fillingSound, fillingSound, false);
            self.fillingSoundPitchOffset = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.fillingSound#pitchOffset"), 1);
            self.fillingSoundVolume = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.fillingSound#volume"), 1);
        end;
    end;
	
	self.unloadAnims = self.numTipAnims;
end;

function HatchTipping:delete()
    if self.fillingSound ~= nil then
        delete(self.fillingSound);
    end;
	for _, FillableTrigger in pairs(self.FillableTriggers) do
		removeTrigger(FillableTrigger.node);
	end;
end;

function HatchTipping:readStream(streamId, connection)
	local turnedOn = streamReadBool(streamId);
	self:setIsTurnedOn(turnedOn, true);
end;

function HatchTipping:writeStream(streamId, connection)
	streamWriteBool(streamId, self.isTurnedOn);
end;

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

function HatchTipping:keyEvent(unicode, sym, modifier, isDown)
end;
  
function HatchTipping:update(dt)

    if self.isClient then
		if self:getIsActiveForInput() then	
			if InputBinding.hasEvent(InputBinding.ACTIVATE_OBJECT) then
				if self.fillAbleObjectInRange ~= nil and self:getIsTurnedOnAllowed() then
					self:setIsTurnedOn(not self.isTurnedOn);
				end;
			end;
		end;
    end;
end;

function HatchTipping:updateTick(dt)

	--- fill object in range ---
	if self.hatchAnimIdx ~= nil and self.fillAbleObjectInRange ~= nil then
		if not self:getIsTurnedOnAllowed() then
			if self.isTurnedOn then
				self:setIsTurnedOn(false);
			end;
		else
			if self.isTurnedOn then
				local fillableObject = self.fillAbleObjectInRange;
				local fillDelta = 0;
				if self:getRealAnimationTime(self.turnOnAnimation) >= self.hatchDischargeStartTime then
					local m = self.capacity/((self.hatchEndDichargeTime-self.hatchDischargeStartTime)/self.animTurnOnSpeedScale);
					fillDelta = m * dt;
					Utils.setEmittingState(self.dischargePartSystems2[self.currentFillType], true);
					if not self.fillingSoundEnabled and self:getIsActiveForSound() then
						playSample(self.fillingSound, 0, self.fillingSoundVolume, 0);
						setSamplePitch(self.fillingSound, self.fillingSoundPitchOffset);
						self.fillingSoundEnabled = true;
					end;
				else
					fillDelta = 0;
				end;
				if fillDelta > 0 then
					self:setFillLevel(self.fillLevel - fillDelta, self.currentFillType);
					fillableObject:setFillLevel(fillableObject.fillLevel + fillDelta, self.fillFruitType);
				end;
				local liftPercent = (self.fillLevel/self.capacity)*100;
				if liftPercent < self.liftLevel then
					if not self.isBoxLifted then
						self:setLiftBox(not self.isBoxLifted);
					end;
				end;
			end;
		end;
	else
		if self.isTurnedOn then
			self:setIsTurnedOn(false);
		end;
	end;
	if self.isClient then
		if self:getAnimationTime(self.liftBoxAnim) == 0 or self:getAnimationTime(self.liftBoxAnim) == 1 then
			if self.hydraulicSoundEnabled then
				stopSample(self.hydraulicSound);
				self.hydraulicSoundEnabled = false;
			end;
		end;
		if self:getIsActive() then
			if self.hatchAnimIdx ~= nil then
				if self.fillLevel > 0 and self.sugarBeetFillType == self.currentFillType then
					if self.tipMode == self.hatchAnimIdx then
						self:setTipMode(math.abs(self.backAnimIdx), false);
					end;
					self.numTipAnims = 1;
				else
					self.numTipAnims = self.unloadAnims;		
				end;
			end;
		end;
	end;
end;

function HatchTipping:draw()
	if self.isClient then
		if self.fillAbleObjectInRange ~= nil and self:getIsTurnedOnAllowed() then
			if self.isTurnedOn then
				g_currentMission:addHelpButtonText(string.format(g_i18n:getText("stop_filling")), InputBinding.ACTIVATE_OBJECT);
			else
				g_currentMission:addHelpButtonText(string.format(g_i18n:getText("start_filling")), InputBinding.ACTIVATE_OBJECT);
			end;
		end;
	end;
	if self:getIsActive() and not g_currentMission.missionPDA.showPDA then
		if self.fillAbleObjectInRange ~= nil and self:getIsTurnedOnAllowed() then
			local fillableObject = self.fillAbleObjectInRange;
			if self.fillAbleObjectInRange.fillLevel ~= nil then
				self.hudFillLevelBase:render();
				local percent = (self.fillAbleObjectInRange.fillLevel / self.fillAbleObjectInRange.capacity) * 100;
				setTextBold(true);
				setTextAlignment(RenderText.ALIGN_CENTER);
				setTextColor(0, 0, 0, 1);
				renderText(self.hudFillLevelBasePosX + self.hudFillLevelBaseWidth / 2 + 0.003, self.hudFillLevelBasePosY + 0.0083, 0.024, string.format("%d (%d%%)", self.fillAbleObjectInRange.fillLevel, percent));
				setTextColor(1, 1, 1, 1);
				renderText(self.hudFillLevelBasePosX + self.hudFillLevelBaseWidth / 2 + 0.003, self.hudFillLevelBasePosY + 0.0113, 0.024, string.format("%d (%d%%)", self.fillAbleObjectInRange.fillLevel, percent));
				setTextBold(false);
				self.hudFillLevelOverlay.width = self.hudFillLevelBarWidth * (self.fillAbleObjectInRange.fillLevel / self.fillAbleObjectInRange.capacity);
				setOverlayUVs(self.hudFillLevelOverlay.overlayId, 0, 0.05, 0, 1, self.fillAbleObjectInRange.fillLevel / self.fillAbleObjectInRange.capacity, 0.05, self.fillAbleObjectInRange.fillLevel / self.fillAbleObjectInRange.capacity, 1);
				self.hudFillLevelOverlay:render();
				self.hudFillLevelFrame:render();
			end;
		end;
	end;
end;

function HatchTipping:onAttach(attacherVehicle)
end;

function HatchTipping:onDetach()
	HatchTipping.onDeactivateSounds(self);
end;

function HatchTipping:onDeactivateSounds()
	if self.fillingSoundEnabled then
		stopSample(self.fillingSound);
		self.fillingSoundEnabled = false;
	end;
end;

function HatchTipping:getIsTurnedOnAllowed()
	local fillableObject = self.fillAbleObjectInRange;
	if self.hatchAnimIdx ~= nil and self.tipMode == self.hatchAnimIdx and self.tipState == Trailer.TIPSTATE_CLOSED then
		if self.fillLevel > 0 and fillableObject.fillLevel ~= fillableObject.capacity then
			if fillableObject.seeds == nil then
				for fillType,v in pairs(fillableObject.fillTypes) do
					if fillType == self.currentFillType then
						self.fillFruitType = self.currentFillType;
						return true;
					end;
				end;
			else
				for seedType,v in pairs(fillableObject.seeds) do
					if seedType == self.currentFillType then
						self.fillFruitType = self.seedFillType;
						return true;
					end;
				end;
			end;
		end;
	end;
	return false;
end;

function HatchTipping:setIsTurnedOn(isTurnedOn, noEventSend)
	SetTurnedOnEvent.sendEvent(self, isTurnedOn, noEventSend)
	self.isTurnedOn = isTurnedOn;
  
	if self.turnOnAnimation ~= nil and self.playAnimation ~= nil then
		local speed = self.animTurnOnSpeedScale;
		if not self.isTurnedOn then
			speed = -speed;
		end
		self:playAnimation(self.turnOnAnimation, speed, nil, true);
	end;
	if not self.isTurnedOn then
		if self.isBoxLifted then
			self:setLiftBox(not self.isBoxLifted);
		end;
		Utils.setEmittingState(self.dischargePartSystems2[self.currentFillType], false);
		stopSample(self.fillingSound);
		self.fillingSoundEnabled = false;
	end;
end;

function HatchTipping:FillableTrigger(triggerId, otherId, onEnter, onLeave, onStay, otherShapeId)
	if onEnter or onLeave then
		local fillAbleObject = g_currentMission.nodeToVehicle[otherShapeId];
		if fillAbleObject ~= nil then
			if fillAbleObject ~= self and fillAbleObject.setFillLevel ~= nil and fillAbleObject.tipAnimations == nil then
				if onEnter then
					self.fillAbleObjectInRange = (fillAbleObject);
				else
					self.fillAbleObjectInRange = nil;
				end;
			end;
		end;
	end;
end;