--
-- self
-- Class for all self
--
-- @author  Boembchen
-- @date  16/04/09
--
-- Copyright (C) Boembchen/Sven77b

Fendt936 = {};

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

function Fendt936:load(xmlFile)

    self.brakeForce = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.brakeForce"), 10);
    self.motorBrakeForce = self.motor.brakeForce;

    local brakeSound = getXMLString(xmlFile, "vehicle.brakeSound#file");
    if brakeSound ~= nil and brakeSound ~= "" then
	  brakeSound = Utils.getFilename(brakeSound, self.baseDirectory); 
        self.brakeSound = createSample("brakeSound");
        loadSample(self.brakeSound, brakeSound, false);
        self.brakeSoundPitchOffset = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.brakeSound#pitchOffset"), 0);
    end;
    
	self.numTwinWheels = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.twinWheels#count"), 0);
    self.twinWheels = {};
    for i=1, self.numTwinWheels do
        local twinWheelnamei = string.format("vehicle.twinWheels.twinWheel" .. "%d", i);
        self.twinWheels[i] = Utils.indexToObject(self.rootNode, getXMLInt(xmlFile, twinWheelnamei .. "#index"));
        setVisibility(self.twinWheels[i], false);
    end;
	
    self.lightsbrake = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.extra_lights.brake#index"));

    self.exhaustParticleLow = {};
    Utils.loadParticleSystem(xmlFile, self.exhaustParticleLow, "vehicle.exhaustParticleLow", self.rootNode, false, nil, self.baseDirectory);
    self.exhaustParticleHigh = {};
    Utils.loadParticleSystem(xmlFile, self.exhaustParticleHigh, "vehicle.exhaustParticleHigh", self.rootNode, false, nil, self.baseDirectory);

	self.trailerAttacherJoints = {};
      local obj = string.format("vehicle.trailerAttacherJoints.trailerAttacherJoint(%d)", 0);
      self.TAJindex = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, obj.. "#index"));
      self.TAJdomv = Utils.getNoNil(getXMLBool(xmlFile, obj.. "#moveable"),false);
	if self.TAJdomv then
      self.TAJminY = Utils.getNoNil(getXMLFloat(xmlFile, obj.. "#minY"),0);
      self.TAJmaxY = Utils.getNoNil(getXMLFloat(xmlFile, obj.. "#maxY"),0);
	end;

    self.keys = {};
    local i=0;
    while true do
        local baseName = string.format("vehicle.keys.input(%d)", i);
        local inputName = getXMLString(xmlFile, baseName.. "#name");
        if inputName == nil then
            break;
        end;
        local inputKey = getXMLString(xmlFile, baseName.. "#key");
        if Input[inputKey] == nil then
            print("Error: invalid key '" .. inputKey .. "'  for input event '" .. inputName .. "'");
            break;
        end;
        self.keys[inputName] = Input[inputKey];
        i = i+1;
    end;
    
	self.extra_lights = {};
    self.extra_lights.brake = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.extra_lights.brake#index"));
    self.Joint = self.TAJindex;
    self.trailerAttacherJointIndex = 0;
    self.attachedTrailer = nil;

    self.showhelp = false;
    self.hudInfo = Utils.getFilename("hud_help_base.png", self.baseDirectory);
    self.hudInfoPoxX = 0.012;
    self.hudInfoPoxY = 0.1825;
    self.hudInfoWidth = 0.425;
    self.hudInfoHeight = 0.1625;
    self.hudInfoOverlay = Overlay:new("hudInfoOverlay", self.hudInfo, self.hudInfoPoxX, self.hudInfoPoxY, self.hudInfoWidth, self.hudInfoHeight);
    self.twinWheelsActive= false;
    self.drawMirror = getVisibility(self.mirrors[1])
    self.brakeOn = false;
    self.revLimit = 100;
    self.maxRpm3 = self.motor.maxRpm[3];
    self.activeTAJ = 0;

end;

function Fendt936:update(dt)
    if self.isEntered then

        if Input.isKeyPressed(self.keys.rev_up) and self.revLimit < 100 then
          self.revLimit = self.revLimit + 1;
        elseif Input.isKeyPressed(self.keys.rev_down) and self.revLimit > 10 then
          self.revLimit = self.revLimit - 1;
        end;
        self.motor.maxRpm[3] = string.format("%d",(self.revLimit * self.maxRpm3 / 100));

        local brake = false;
        if self.motor.brakeForce == self.brakeForce and getInputAxis(Input.AXIS_Y) ~= 0 then
          brake = true;
          self.motor.maxRpm[3] = 0;
        end;
        if (self.movingDirection*self.lastSpeed*(-getInputAxis(Input.AXIS_Y))) < -0.001 then
           brake = true;
           self.brakeOn = true;
           self.motor.brakeForce = self.brakeForce;
        elseif not brake then
           self.motor.brakeForce = self.motorBrakeForce;
        end;
        local brake = false;
        if self.motor.brakeForce == self.brakeForce and getInputAxis(Input.AXIS_Y) ~= 0 then
          brake = true;
          self.motor.maxRpm[3] = 0;
        end;
        if (self.movingDirection*self.lastSpeed*(-getInputAxis(Input.AXIS_Y))) < -0.001 then
           brake = true;
           self.brakeOn = true;
           self.motor.brakeForce = self.brakeForce;
        elseif not brake then
           self.motor.brakeForce = self.motorBrakeForce;
        end;
        setVisibility(self.extra_lights.brake, brake);
        if self.brakeOn and not brake then
            if self.brakeSound ~= nil then
                setSamplePitch(self.brakeSound, self.brakeSoundPitchOffset);
                playSample(self.brakeSound, 1, 1, 0);
            end;
            self.brakeOn = false;
        end;
        if getInputAxis(Input.AXIS_Y) ~= 0 and not brake then
        		Utils.setEmittingState(self.exhaustParticleLow, false);
        		Utils.setEmittingState(self.exhaustParticleHigh, true);
        else
        		Utils.setEmittingState(self.exhaustParticleLow, false);
        		Utils.setEmittingState(self.exhaustParticleHigh, false);
        end;


        if self.attachedTrailer == nil then
            local nearestTrailer = nil;
            local nearestDistance = 0.4;
                local px, py, pz = getWorldTranslation(self.TAJindex);
                for t=1, table.getn(g_currentMission.attachables) do
                    local vx, vy, vz = getWorldTranslation(g_currentMission.attachables[t].attacherJoint);
                    local distance = Utils.vector2Length(px-x, pz-z);
                    if distance < nearestDistance then
                        self.Joint = self.TAJindex;
                        self.activeTAJ = 0;
                        nearestDistance = distance;
                end;
            end;
        end;

        if Input.isKeyPressed(self.keys.moveAK_up) or Input.isKeyPressed(self.keys.moveAK_dn) then
            setJointFrame(self.trailerAttacherJointIndex,0,self.Joint);
            local ymod = 0;
            if Input.isKeyPressed(self.keys.moveAK_up) then ymod = 0.01; else ymod = -0.01; end;
                if self.TAJdomv then
                    local x,y,z = getTranslation(self.TAJindex);
                    y = y + ymod;
                    if y > self.TAJminY and y < self.TAJmaxY then
                        setTranslation(self.TAJindex,x,y,z);
                end;
            end;
        end;
        
		if self.twinWheelsActive then
		for i=1, self.numTwinWheels do
			local twinWheel = self.twinWheels[i];
			setVisibility(twinWheel, self.twinWheelsActive);
		end;
	else
		for i=1, self.numTwinWheels do
			local twinWheel = self.twinWheels[i];
			setVisibility(twinWheel, self.twinWheelsActive, false);
		end;
	end;
	
        if self.rundumleuchtenAn then
          for i=1, self.rundumleuchtenAnz do
            rotate(self.rundumleuchten[i].rotNode, 0, dt*self.rundumleuchten[i].speed, 0);
          end;
        end;



end;

end;

function Fendt936:draw()

    g_currentMission:addExtraPrintText("Drehzahlbegrenzer: "..string.format("%d Prozent",self.revLimit));
    if not self.showhelp then
    	g_currentMission:addExtraPrintText("Taste "..string.upper(string.char(self.keys.hilfe))..": Hilfebox einblenden");
    else
    	self.hudInfoOverlay:render();
    	local helptext={};
		helptext[1] = "Taste "..key_convert(self.keys.rearlight)..": Arbeitslicht hinten";
    	helptext[2] = "Nyomd meg a "..key_convert(self.keys.rundumleuchte)..": Rundumleuchte";
    	helptext[3] = "Nyomd meg a "..key_convert(self.keys.spiegel)..":Warntafel";
    	helptext[4] = "Nyomd meg a "..key_convert(self.keys.moveAK_up).."|"..key_convert(self.keys.moveAK_dn)..": Anhängerkupplung heben/senken";
    	helptext[5] = "Nyomd meg a "..key_convert(self.keys.rev_up).."|"..key_convert(self.keys.rev_down)..": Drehzahlbegrenzer heben/senken";
    	helptext[6] = "Nyomd meg a "..key_convert(self.keys.hilfe)..": Hilfebox ausblenden";
		helptext[7] = "Nyomd meg a "..key_convert(self.keys.frontlight)..":Zwillingsreifen";
		if self.rearlightActive then
    		 helptext[1] = helptext[1].." (an)";
    	else
    		 helptext[1] = helptext[1].." (aus)";
    	end;
    	if self.rundumleuchtenAn then
    		 helptext[2] = helptext[2].." (an)";
    	else
    		 helptext[2] = helptext[2].." (aus)";
    	end;
    	if self.frontlightActive then
    		 helptext[7] = helptext[7].." (an)";
    	else
    		 helptext[7] = helptext[7].." (aus)";
    	end;
    	for i=1, table.getn(helptext) do
    		renderText((self.hudInfoPoxX+0.05),((self.hudInfoPoxY+self.hudInfoHeight) - (0.02*i)),0.02,helptext[i]);
    	end;
    end;

end;

function Fendt936:onEnter()
    Utils.setEmittingState(self.exhaustParticleLow, false);
end;

function Fendt936:onLeave()
    self.licht1 = false;
    self.licht2 = false;
	self.frontlightActive = false;
    self.rearlightActive = false;
    for i=1, self.rundumleuchtenAnz do
       setVisibility(self.rundumleuchten[i].light, self.rundumleuchtenAn);
    end;
    Utils.setEmittingState(self.exhaustParticleLow, false);
end;

function Fendt936:delete()
end;


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

function key_convert(key)
    if key ~= nil then 
	    local keyname = "";
	    if key > 32 and key < 123 then
	    	keyname = string.upper(string.char(key));
	    elseif key > 255 and key < 266 then
	    	keyname = "NUM "..string.char(key-208);
	    else 
	    	keyname = "";
	    end;
	    return(keyname);
	  end;
end;



