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

Unimog_TERRA = {};

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

function Unimog_TERRA:load(xmlFile)

    self.rundumleuchtenAnz = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.rundumleuchten#count"),0);
    self.rundumleuchtenAn = false;
    self.rundumleuchten = {};
    for i=1, self.rundumleuchtenAnz do
        local objname = string.format("vehicle.rundumleuchten.light" .. "%d",i);
        self.rundumleuchten[i] = {};
        self.rundumleuchten[i].rotNode = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, objname .. "#rotNode"));
        self.rundumleuchten[i].light = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, objname .. "#light"));
        self.rundumleuchten[i].source = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, objname .. "#lightsource"));
        self.rundumleuchten[i].speed = Utils.getNoNil(getXMLInt(xmlFile,  objname .. "#rotSpeed"), 1)/1000;
        self.rundumleuchten[i].emit = Utils.getNoNil(getXMLBool(xmlFile, objname .. "#emitLight"), true);
        if not self.rundumleuchten[i].emit and self.rundumleuchten[i].source ~= nil then
           setVisibility(self.rundumleuchten[i].source, false);
        end;
    end;

    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.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.numTerraWheels = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.terraWheels#count"), 0);
    self.terraWheels = {};
    for i=1, self.numTerraWheels do
        local terraWheelnamei = string.format("vehicle.terraWheels.terraWheel" .. "%d", i);
        self.terraWheels[i] = Utils.indexToObject(self.rootNode, getXMLInt(xmlFile, terraWheelnamei .. "#index"));
        setVisibility(self.terraWheels[i], false);
    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.Joint = self.TAJindex;
    self.trailerAttacherJointIndex = 0;
    self.attachedTrailer = nil;

    self.mirrors = {};
    self.mirrors[1] = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.mirrors.mirror1#index"));
    self.mirrors[2] = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.mirrors.mirror2#index"));

    self.Nwheels = {};
    self.Nwheels[1] = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.Nwheels.Nwheel1#index"));
    self.Nwheels[2] = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.Nwheels.Nwheel2#index"));
    self.Nwheels[3] = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.Nwheels.Nwheel3#index"));	
    self.Nwheels[4] = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.Nwheels.Nwheel4#index"));
	
    self.terraWheelsActive= false;
    self.drawNwheel = getVisibility(self.Nwheels[1])
    self.drawMirror = getVisibility(self.mirrors[1])
    self.brakeOn = false;
    self.rearlightActive = false;
    self.revLimit = 100;
    self.maxRpm3 = self.motor.maxRpm[3];
    self.activeTAJ = 0;

end;

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

    if isDown and sym == self.keys.rundumleuchte then
      self.rundumleuchtenAn = not self.rundumleuchtenAn;
      for i=1, self.rundumleuchtenAnz do
        setVisibility(self.rundumleuchten[i].light, self.rundumleuchtenAn);
      end;
    end;
    
    if isDown and sym == self.keys.spiegel then
    	self.drawMirror = not self.drawMirror;
    	setVisibility(self.mirrors[1], self.drawMirror);
    	setVisibility(self.mirrors[2], self.drawMirror);
    end;
	
	if isDown and sym == self.keys.terraWheels then 
		self.terraWheelsActive = not self.terraWheelsActive;
	end;
	
    if isDown and sym == self.keys.terraWheels then
    	self.drawNwheel = not self.drawNwheel;
    	setVisibility(self.Nwheels[1], self.drawNwheel);
    	setVisibility(self.Nwheels[2], self.drawNwheel);
    	setVisibility(self.Nwheels[3], self.drawNwheel);
    	setVisibility(self.Nwheels[4], self.drawNwheel);		
    end;	
    
    if isDown and sym == Input.KEY_0 then
		self.helpPanel = not self.helpPanel;
	end;

end;


function Unimog_TERRA: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;
        setVisibility(self.lightsbrake, 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.terraWheelsActive then
		for i=1, self.numTerraWheels do
			local terraWheel = self.terraWheels[i];
			setVisibility(terraWheel, self.terraWheelsActive);
		end;
	else
		for i=1, self.numTerraWheels do
			local terraWheel = self.terraWheels[i];
			setVisibility(terraWheel, self.terraWheelsActive, 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 Unimog_TERRA:draw()

    if self.isEntered then
		if not self.helpPanel then
			renderText(0.8335, 0.15, 0.02, "Taste 0: Info Einschalten");
		else
			renderText(0.8335, 0.15, 0.02, "Taste 0: Info Abschalten");
		end;
		if self.helpPanel then
			renderText(0.72, 0.84, 0.025, "- Unimog 1600 2 Info -");
			renderText(0.72, 0.815, 0.02, "Taste 4: Kupplung Heben");	
			renderText(0.72, 0.8, 0.02, "Taste 5: Kupplung Senken");			
			renderText(0.72, 0.785, 0.02, "Taste 6: Rundumleuchte ein/aus");
			renderText(0.72, 0.77, 0.02, "Tasten "..key_convert(self.keys.rev_down).."/"..key_convert(self.keys.rev_up)..": "..string.format("%d Prozent", self.revLimit));
			renderText(0.72, 0.77, 0.02, "Tasten "..key_convert(self.keys.rev_down).."/"..key_convert(self.keys.rev_up)..": "..string.format("%d Prozent", self.revLimit));
			renderText(0.72, 0.755, 0.02, "Taste T: Normal-/Terrabereifung");
			renderText(0.72, 0.74, 0.02, "Taste U: Spiegel ein/ausblenden");			
		end;
	end;	

end;

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

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

function Unimog_TERRA:delete()
end;


function Unimog_TERRA: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;



