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

Umog1600KD = {};

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

function Umog1600KD: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.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.rear = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.extra_lights.rear#index"));
    self.extra_lights.front = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.extra_lights.front#index"));
    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.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.twins = {};
    self.twins[1] = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.twins.twin1#index"));
    self.twins[2] = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.twins.twin2#index"));
    self.twins[3] = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.twins.twin3#index"));
    self.twins[4] = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.twins.twin4#index"));



    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.drawMirror = getVisibility(self.mirrors[1])
    self.brakeOn = false;
    self.rearlightActive = false;
    self.frontlightActive = false;
    self.licht1 = false;
    self.licht2 = false;
    self.brakeOn = false;
    self.revLimit = 100;
    self.maxRpm3 = self.motor.maxRpm[3];
    self.activeTAJ = 0;
    self.drawTwins = getVisibility(self.twins[1])
end;

function Umog1600KD: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.rearlight then
      self.rearlightActive = not self.rearlightActive;
      setVisibility(self.extra_lights.rear, self.rearlightActive);
    end;
	
	if isDown and sym == self.keys.frontlight then
      self.frontlightActive = not self.frontlightActive;
      setVisibility(self.extra_lights.front, self.frontlightActive);
    end;
	
    if isDown and sym == self.keys.Warntafel 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.Zwillinge then
    	self.drawTwins = not self.drawTwins;
    	setVisibility(self.twins[1], self.drawTwins);
    	setVisibility(self.twins[2], self.drawTwins);
		setVisibility(self.twins[3], self.drawTwins);
    	setVisibility(self.twins[4], self.drawTwins);
    end;
    
    
    if isDown and sym == self.keys.hilfe then
      if self.hudInfoOverlay ~= nil then
      	self.showhelp = not self.showhelp;
      end;
    end;

end;


function Umog1600KD: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.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 Umog1600KD: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] = "Taste "..key_convert(self.keys.rundumleuchte)..": Rundumleuchte";
    	helptext[3] = "Taste "..key_convert(self.keys.Warntafel)..": Warntafel";
    	helptext[4] = "Tasten "..key_convert(self.keys.moveAK_up).."|"..key_convert(self.keys.moveAK_dn)..": Anhängerkupplung heben/senken";
    	helptext[5] = "Tasten "..key_convert(self.keys.rev_up).."|"..key_convert(self.keys.rev_down)..": Drehzahlbegrenzer heben/senken";
    	helptext[6] = "Taste "..key_convert(self.keys.hilfe)..": Hilfebox ausblenden";
		helptext[7] = "Taste "..key_convert(self.keys.frontlight)..": Arbeitslicht vorne";
		helptext[8] = "Taste "..key_convert(self.keys.Zwillinge)..": Zwillinge";
    	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.drawMirror then
    		 helptext[3] = helptext[3].." (an)";
    	else
    		 helptext[3] = helptext[3].." (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;
		if self.drawTwins then
    		 helptext[8] = helptext[8].." (an)";
    	else
    		 helptext[8] = helptext[8].." (aus)";
    	end;
    end;

end;

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

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

function Umog1600KD:delete()
end;


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



