--
-- Brix Stein-Gigant 3m
-- Specialization for BrixSteinGigant3m mod
--
-- @author Templaer
-- @version 1.0
-- @date  08/08/10

BrixSteinGigant = {};

function BrixSteinGigant.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Attachable, specializations);
end;

function BrixSteinGigant:load(xmlFile)
	self.updateSafeArea = SpecializationUtil.callSpecializationsFunction("updateSafeArea");
	
	local MiddlePartXNode = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.MiddlePart#index"));
    if MiddlePartXNode ~= nil then
        self.MiddlePart = {};
        self.MiddlePart.node = MiddlePartXNode;
        local x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.MiddlePart#minRot"));
        self.MiddlePart.minRot = {};
        self.MiddlePart.minRot[1] = Utils.degToRad(Utils.getNoNil(x, 0));
        self.MiddlePart.minRot[2] = Utils.degToRad(Utils.getNoNil(y, 0));
        self.MiddlePart.minRot[3] = Utils.degToRad(Utils.getNoNil(z, 0));

        x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.MiddlePart#maxRot"));
        self.MiddlePart.maxRot = {};
        self.MiddlePart.maxRot[1] = Utils.degToRad(Utils.getNoNil(x, 0));
        self.MiddlePart.maxRot[2] = Utils.degToRad(Utils.getNoNil(y, 0));
        self.MiddlePart.maxRot[3] = Utils.degToRad(Utils.getNoNil(z, 0));

        self.MiddlePart.rotTime = Utils.getNoNil(getXMLString(xmlFile, "vehicle.MiddlePart#rotTime"), 2)*1000;
        self.MiddlePart.touchRotLimit = Utils.degToRad(Utils.getNoNil(getXMLString(xmlFile, "vehicle.MiddlePart#touchRotLimit"), 10));
    end;
	
	local cultivatorSound = getXMLString(xmlFile, "vehicle.cultivatorSound#file");
    if cultivatorSound ~= nil and cultivatorSound ~= "" then
        cultivatorSound = Utils.getFilename(cultivatorSound, self.baseDirectory);
        self.cultivatorSound = createSample("cultivatorSound");
        loadSample(self.cultivatorSound, cultivatorSound, false);
        self.cultivatorSoundPitchOffset = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.cultivatorSound#pitchOffset"), 0);
        self.cultivatorSoundVolume = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.cultivatorSound#volume"), 1.0);
        self.cultivatorSoundEnabled = false;
    end;
			
    self.groundParticleSystems = {};
    local psName = "vehicle.groundParticleSystem";
    Utils.loadParticleSystem(xmlFile, self.groundParticleSystems, psName, self.components, false, nil, self.baseDirectory)
    self.groundParticleSystemActive = false;	
	
    self.speedRotatingParts = {};
    local i=0;
    while true do
        local baseName = string.format("vehicle.speedRotatingParts.speedRotatingPart(%d)", i);
        local index = getXMLString(xmlFile, baseName.. "#index");
        if index == nil then
            break;
        end;
        local node = Utils.indexToObject(self.components, index);
        if node ~= nil then
            local entry = {};
            entry.node = node;
            entry.rotationSpeedScale = getXMLFloat(xmlFile, baseName.."#rotationSpeedScale");
            if entry.rotationSpeedScale == nil then
                entry.rotationSpeedScale = 1.0/Utils.getNoNil(getXMLFloat(xmlFile, baseName.."#radius"), 1);
            end;

            entry.foldMinLimit = Utils.getNoNil(getXMLFloat(xmlFile, baseName .. "#foldMinLimit"), 0);
            entry.foldMaxLimit = Utils.getNoNil(getXMLFloat(xmlFile, baseName .. "#foldMaxLimit"), 1);

            table.insert(self.speedRotatingParts, entry);
        end;
        i = i+1;
    end;
	
	self.aiTerrainDetailChannel1 = g_currentMission.ploughChannel;
    self.aiTerrainDetailChannel2 = g_currentMission.sowingChannel;
	
    self.speedViolationMaxTime = 2500;
    self.speedViolationTimer = self.speedViolationMaxTime;
	
	self.charIdAnim = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.animWorkingDiscs#Node"));
	self.clipIndexAnim = getXMLString(xmlFile, "vehicle.animWorkingDiscs#animationClip");
	
	self.isDown = false;
	self.safeMode = false;
	self.wasTooFast = false;
end;

function BrixSteinGigant:delete()
	Utils.deleteParticleSystem(self.groundParticleSystems);

    if self.cultivatorSound ~= nil then
        delete(self.cultivatorSound);
    end;
end;

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

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

function BrixSteinGigant:update(dt)
	if self:getIsActiveForInput() then
		if InputBinding.hasEvent(InputBinding.LOWER_IMPLEMENT) then
			self.isDown = not self.isDown;
		end;
		
		if InputBinding.hasEvent(InputBinding.SAFE_MODE) then
			self.safeMode = not self.safeMode;
		end;
	end;
	
	if self:getIsActive() then
		if self.isDown then
			for k, cuttingArea in pairs(self.cuttingAreas) do
				local x,y,z = getWorldTranslation(cuttingArea.start);
				local x1,y1,z1 = getWorldTranslation(cuttingArea.width);
				local x2,y2,z2 = getWorldTranslation(cuttingArea.height);
				if self.safeMode then
					self:updateSafeArea(x, z, x1, z1, x2, z2);
				else
					Utils.updateCultivatorArea(x, z, x1, z1, x2, z2);
				end;
			end;

			if InputBinding.isPressed(InputBinding.CARRIERWORKMODEON) then
				self.MiddlePartMax = true;												
			else
				self.MiddlePartMax = false;				
			end;
			if InputBinding.isPressed(InputBinding.CARRIERWORKMODEOFF) then
				self.MiddlePartMin = true;				
			else
				self.MiddlePartMin = false;			
			end;
			
			local doRotate = self.MiddlePartMax or self.MiddlePartMin 
			if self.MiddlePart ~= nil and doRotate then
				local x, y, z = getRotation(self.MiddlePart.node);
				local rot = {x,y,z};
				local newRot = Utils.getMovedLimitedValues(rot, self.MiddlePart.maxRot, self.MiddlePart.minRot, 3, self.MiddlePart.rotTime, dt, not self.MiddlePartMax);
				setRotation(self.MiddlePart.node,unpack(newRot));
			end;
			
			if self:doCheckSpeedLimit() and self.lastSpeed*3600 > 30 then
				self.speedViolationTimer = self.speedViolationTimer - dt;
				if self.speedViolationTimer < 0 then
					if self.attacherVehicle then
						self.attacherVehicle:detachImplementByObject(self);
					end;
				end;
			else
				self.speedViolationTimer = self.speedViolationMaxTime;
			end;

            for k,v in pairs(self.speedRotatingParts) do
                if foldAnimTime == nil or (foldAnimTime <= v.foldMaxLimit and foldAnimTime >= v.foldMinLimit) then
                    rotate(v.node, v.rotationSpeedScale * self.lastSpeedReal * self.movingDirection * dt, 0, 0);
                end;
            end;
		local charId = getAnimCharacterSet(self.charIdAnim);
		local clipIndex = getAnimClipIndex(charId, self.clipIndexAnim);		
			if self.lastSpeed*3600 > 8 then
				assignAnimTrackClip(charId , 0, clipIndex);
				setAnimTrackLoopState(charId, 0, true);
				setAnimTrackSpeedScale(charId, 0, 6);
				enableAnimTrack(charId, 0);
			else
				disableAnimTrack(charId, 0);
			end;			
			if self:getIsActiveForSound() then
				if self.cultivatorSound ~= nil and not self.cultivatorSoundEnabled then
					if self.lastSpeed * 3600 > 3 then
						playSample(self.cultivatorSound, 0, self.cultivatorSoundVolume, 0);
						setSamplePitch(self.cultivatorSound, self.cultivatorSoundPitchOffset);
						self.cultivatorSoundEnabled = true;
					end;
				end;
			end;
			
			if self.lastSpeed*3600 > 5 and not self.groundParticleSystemActive then
				self.groundParticleSystemActive = true;
				Utils.setEmittingState(self.groundParticleSystems, true);
			end;

			if self.lastSpeed*3600 < 5 and self.groundParticleSystemActive then
				self.groundParticleSystemActive = false;
				Utils.setEmittingState(self.groundParticleSystems, false);
			end;
		else
			self.speedViolationTimer = self.speedViolationMaxTime;
			
			if self.cultivatorSoundEnabled then
				stopSample(self.cultivatorSound);
				self.cultivatorSoundEnabled = false;
			end;

			if self.groundParticleSystemActive then
				self.groundParticleSystemActive = false;
				Utils.setEmittingState(self.groundParticleSystems, false);
			end;
		end;
	else
		if self.groundParticleSystemActive then
			self.groundParticleSystemActive = false;
			Utils.setEmittingState(self.groundParticleSystems, false);
		end;
	end;
	
	if self.cultivatorSoundEnabled then
		if self.lastSpeed*3600 < 3 then
			stopSample(self.cultivatorSound);
			self.cultivatorSoundEnabled = false;
		end;
	end;
end;

function BrixSteinGigant:draw()
	if self.isDown then
		g_currentMission:addHelpButtonText(g_i18n:getText("LiftCultivator"), InputBinding.LOWER_IMPLEMENT);
	else
		g_currentMission:addHelpButtonText(g_i18n:getText("LowerCultivator"), InputBinding.LOWER_IMPLEMENT);
	end;
	
	if self.safeMode then
		g_currentMission:addHelpButtonText(g_i18n:getText("SafeModeOff"), InputBinding.SAFE_MODE);
	else
		g_currentMission:addHelpButtonText(g_i18n:getText("SafeModeOn"), InputBinding.SAFE_MODE);
	end;
	
    if math.abs(self.speedViolationTimer - self.speedViolationMaxTime) > 2 then
        g_currentMission:addWarning(g_i18n:getText("Dont_drive_to_fast") .. "\n" .. string.format(g_i18n:getText("Cruise_control_levelN"), "2", InputBinding.getButtonKeyName(InputBinding.SPEED_LEVEL1)), 0.07+0.022, 0.019+0.029);
    end;
end;

function BrixSteinGigant:updateSafeArea(startWorldX, startWorldZ, widthWorldX, widthWorldZ, heightWorldX, heightWorldZ)
  local cultiId = g_currentMission.cultivatorChannel;
  local sowingId = g_currentMission.sowingChannel;
  local detailId = g_currentMission.terrainDetailId;
  local ploughId = g_currentMission.ploughChannel;
  local sprayId = g_currentMission.sprayChannel;
  
  local x, z, widthX, widthZ, heightX, heightZ = Utils.getXZWidthAndHeight(detailId, startWorldX, startWorldZ, widthWorldX, widthWorldZ, heightWorldX, heightWorldZ);
  
  Utils.updateDestroyCommonArea(startWorldX, startWorldZ, widthWorldX, widthWorldZ, heightWorldX, heightWorldZ);
  
  setDensityMaskedParallelogram(detailId, x, z, widthX, widthZ, heightX, heightZ, cultiId, 1, detailId, sowingId, 1, 1);
  setDensityParallelogram(detailId, x, z, widthX, widthZ, heightX, heightZ, sowingId, 1, 0);
  setDensityParallelogram(detailId, x, z, widthX, widthZ, heightX, heightZ, ploughId, 1, 0);
  setDensityParallelogram(detailId, x, z, widthX, widthZ, heightX, heightZ, sprayId, 1, 0);
end;