/* Insérer ici les fonctions spécifiques à cette activité. Elles peuvent marcher
avec les fonctions et variables déjà définies dans 'activity_functions.js' du
dossier 'res'.*/

// Gets the modal (intiated as the intro_modal at first)
var modal = document.getElementById("intro_modal");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// Displays the modal when DOM is Loaded
document.addEventListener('DOMContentLoaded', event => {
  modal.style.display = "block";
});
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

runButton.style.background = 'linear-gradient(to bottom, #77B55B 5%, #568241 100%)';
runButton.style.border = '3px solid #476B36';
connectButton.style.background = 'linear-gradient(to bottom, #737375 5%, #5D5C5E 100%)';
connectButton.style.border = '3px solid #353436';


var firstTime;
var curSpeed;
var curPos;
var fuel_ratio;
var power_ratio;
var simu_timeouts = [];

var sky_rect


var fuel_rect
var fuel_box
var fuel_text

var power_rect
var power_box
var power_text

var speed_label_text
var speed_text
var speed_unit_text

var lander_img
var earth_img

var fuel_gradient
var power_gradient
var sky_gradient


var canvas = SVG().addTo('#animationArea').size(660, 490)

function init_canvas() {
  fuel_gradient = canvas.gradient('linear', function(add) {
    add.stop(0, '#ff2e27')
    add.stop(1, '#ffde00')
  })
  power_gradient = canvas.gradient('linear', function(add) {
    add.stop(0, '#3c8001')
    add.stop(1, '#93f45e')
  })
  sky_gradient = canvas.gradient('linear', function(add) {
    add.stop(0, '#000D47')
    add.stop(1, '#00051C')
  }).from(0, 1).to(0, 0)
  sky_rect = canvas.rect(650, 350).fill(sky_gradient).stroke({ width: 3, color: '#333' }).attr({x: 5, y: 5})
  
  fuel_rect = canvas.rect(490, 50).attr({x: 160, y: 435, fill: fuel_gradient})
  fuel_box = canvas.rect(490, 50).fill('none').stroke({ width: 3, color: '#333' }).attr({x: 160, y: 435})
  fuel_text = canvas.text("Carburant du module :").attr({x: 0, y: 445})
  
  power_rect = canvas.rect(490, 50).attr({x: 160, y: 370, fill: power_gradient})
  power_box = canvas.rect(490, 50).fill('none').stroke({ width: 3, color: '#333' }).attr({x: 160, y: 370})
  power_text = canvas.text("Puissance moteurs :").attr({x: 0, y: 380})
  
  speed_label_text = canvas.text("Vitesse :").attr({x:505, y : 110}).font({fill : "#FFFFFF", weight: "bold", size : "25px"})
  speed_text = canvas.text("00.00").attr({x:510, y : 130}).font({fill : "#FFFFFF", weight: "bold", size : "40px"})
  speed_unit_text = canvas.text("km/h").attr({x:535, y : 180}).font({fill : "#FFFFFF", size : "20px"})

  lander_img = canvas.image('img/lander.png').size(30, 30).attr({x: 325, y : 0})

  earth_img = canvas.image('img/earth.png').size(90, 90).attr({x: 100, y : 50})
}

init_canvas()

function enableManual() {
  manual_enabled = true;
  //alert("Augmenter/diminuer la puissance : 'Haut/Bas'");
}

document.addEventListener('keydown', function(event) {
  if (manual_enabled) {
    if(event.keyCode == 38) {
      changePower(power_ratio+0.02)
  }
    else if(event.keyCode == 40) {
        changePower(power_ratio-0.02)
    } 
  }
    
});

function init_var() {
  for (var i=0; i<simu_timeouts.length; i++) {
  clearTimeout(simu_timeouts[i]);
  }
  console.log("Initialisation de la simulation")
  firstTime = (new Date()).getTime()
  curPos = 1;
  curSpeed = -0.03;
  canvas.clear()
  init_canvas()
  changePower(0, 0)
  changeFuel(1, 0)
  stepSimulation(getCurTime())
}


function getCurTime() {
  return(new Date()).getTime() - firstTime;
}

function update_speed(deltaT) {
  if (curPos <= 0 && curSpeed < 0 && power_ratio<=0.2) curSpeed = 0
  else curSpeed = curSpeed + (power_ratio-0.2)*deltaT*0.04
  var disp_speed = Math.round((-(curSpeed*200) + Number.EPSILON) * 100) / 100
  if (disp_speed <= 4.0) {
    speed_text.text(""+ disp_speed).font({fill : "#FFFFFF", weight: "bold", size : "40px"})
  } else {
    speed_text.text(""+ disp_speed).font({fill : "#FF7777", weight: "bold", size : "40px"})
  }
  

}

function update_pos(deltaT) {
  curPos = Math.max(curPos + curSpeed*deltaT, 0);

}

function update_fuel(deltaT) {
  changeFuel(fuel_ratio - power_ratio*deltaT*0.10, 0)
  if (fuel_ratio <= 0) {
    changePower(0, 200)
  }
}

function isFuelEmpty() {
  return fuel_ratio <= 0;
}



function stepSimulation(prevTime) {
  var t = getCurTime()
  var deltaT = t - prevTime
  update_speed(deltaT/1000)
  update_pos(deltaT/1000)
  update_fuel(deltaT/1000)
  var height = (1-curPos)*350
  lander_img.attr({y : height})
  if (curPos >= 1.05) {
    alert("Vous allez dans le mauvais sens ! Il faut se poser et non décoller ;)")
  } else if (curPos <= 0.07) {
    if (curSpeed <= -0.02) { //4 km/h
      lander_img.load("img/explosion.png", () => {
        alert("Vous vous êtes écrasé ! Vous alliez trop vite ! :(")
      })
      
    } else {
      alert("Bravo ! Vous avez aluni à la bonne vitesse !")
    }
  } else {
    simu_timeouts.push(setTimeout(function() {stepSimulation(t)}, 40))
  }
}


function getLanderSpeed() {
  return -(curSpeed*200)
}

function isLanderLanded() {
  return (curPos <= 0.07)
}



function changeFuel(ratio, duration) {
  fuel_ratio = Math.max(ratio, 0);
  if (duration <= 0 ) {
    fuel_rect.width(fuel_box.width()*fuel_ratio);
  } else {
    fuel_rect.animate(duration, 0, 'now').width(fuel_box.width()*fuel_ratio);
  }
}

function changePower(ratio, duration) {
  power_ratio =  Math.max(ratio, 0);
  power_ratio = Math.min(ratio, 1);
  power_rect.animate(duration, 0, 'now').width(power_box.width()*power_ratio);
}

