/* 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'.*/

var modal = document.getElementById("intro_modal");
var span = document.getElementsByClassName("close")[0];

document.addEventListener('DOMContentLoaded', event => {
  modal.style.display = "block";
  canvas = SVG().addTo('#animationArea').size(660, 510)
  initCanvas();
});
span.onclick = function() {
  modal.style.display = "none";
}
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

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)
    } else if (event.keyCode == 32) {
      if (rocketLaunched) changeRocketStage()
      else launchRocket()
    }
  }
    
});


var canvas;
var firstTime;
var curSpeed;
var curPos;
var curStage;
var fuel_ratio;
var power_ratio;
var rocketLaunched;
var simu_timeouts = [];
var manual_enabled;

var sky_rect;
var maxq_rect;
var maxq_text;
var path;
var rocket;
var length;

var fuel_rect;
var fuel_box;
var fuel_text;

var power_rect;
var power_box;
var power_text;

var rocket_img;




/*Fonctions liées à l'animation, la simu et à sa gestion */



function initCanvas() {
  var fuel_gradient = canvas.gradient('linear', function(add) {
    add.stop(0, '#ff2e27')
    add.stop(1, '#ffde00')
  })
  var power_gradient = canvas.gradient('linear', function(add) {
    add.stop(0, '#3c8001')
    add.stop(1, '#93f45e')
  })
  var sky_gradient = canvas.gradient('linear', function(add) {
    add.stop(0, '#4cdaff')
    add.stop(1, '#001b91')
  }).from(0, 1).to(0, 0)
  sky_rect = canvas.rect(500, 350).fill(sky_gradient).stroke({ width: 3, color: '#333' }).attr({x: 5, y: 5})
  maxq_rect = canvas.rect(500, 30).stroke({ width: 3, color: '#555' }).attr({x: 5, y: 220, fill:'#FFA343', })
  maxq_text = canvas.text("Zone de max Q").attr({x: 350, y:220})
  path = canvas.path("M40,353 C40,70 300,48 503,41").fill('none').stroke({width:5, color: '#ff0000'})
  rocket = canvas.image('img/r0.png').size(30, 1000).center(40,353)
  length = path.length()
  
  fuel_rect = canvas.rect(490, 50).attr({x: 160, y: 450, fill: fuel_gradient})
  fuel_box = canvas.rect(490, 50).fill('none').stroke({ width: 3, color: '#333' }).attr({x: 160, y: 450})
  fuel_text = canvas.text("Carburant de l'étage :").attr({x: 0, y: 460})
  
  power_rect = canvas.rect(490, 50).attr({x: 160, y: 395, fill: power_gradient})
  power_box = canvas.rect(490, 50).fill('none').stroke({ width: 3, color: '#333' }).attr({x: 160, y: 395})
  power_text = canvas.text("Puissance moteurs :").attr({x: 0, y: 405})
  
  rocket_img = canvas.image('img/r0.png').attr({x: 550, y : 0})
}

/**
 * Fonction appelée à chaque lancement du code.
 */

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()
  manual_enabled = false;
  curPos = 0;
  curSpeed = 0;
  curStage = 1;
  rocketLaunched = false;
  canvas.clear();
  initCanvas();
  changeFuel(1, 0)
  changePower(0, 0)
  stepSimulation(getCurTime())
}

function enableManual() {
  manual_enabled = true;
  alert("Lancer et séparer les étage : 'Espace' - Augmenter/diminuer la puissance : 'Haut/Bas'");
}

function launchRocket() {
  rocketLaunched = true;
  changeRocketImg(1);
}


function changeRocketStage() {
  curStage = (curStage < 4)?(curStage+1):4;
  changeRocketImg(curStage)
  if (curStage < 4) changeFuel(1, 200)
}

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) {
  if (rocketLaunched || ratio == 0) {
    power_ratio =  Math.max(ratio, 0);
    power_ratio = Math.min(power_ratio, 1);
    power_rect.animate(duration, 0, 'now').width(power_box.width()*power_ratio);
  }
}

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

function isInMaxQ() {
  return curPos>0.13 && curPos<0.24
}

function isInOrbit() {
  return curPos>=1;
}


function update_speed(deltaT) {
  if (curPos <= 0 && curSpeed < 0 && power_ratio<=0.5) curSpeed = 0
  else if (!rocketLaunched) curSpeed = 0
  else if (fuel_ratio > 0) curSpeed = curSpeed + (power_ratio-0.5)*deltaT*0.01
  else curSpeed = curSpeed + (0-0.5)*deltaT*0.01

}

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

}

function update_fuel(deltaT) {
  if (fuel_ratio >= 0) {
    changeFuel(fuel_ratio - power_ratio*deltaT*0.12, 0)
  } else {
    changeFuel(0, 0);
  }
}

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



function stepSimulation(prevTime) {
  var t = getCurTime()
  var deltaT = t - prevTime
  update_speed(deltaT/1000)
  update_pos(deltaT/1000)
  update_fuel(deltaT/1000)
  var p = path.pointAt(curPos*length)
  rocket.center(p.x, p.y)
  //console.log('pos' + curPos + 'speed' + curSpeed)
  if (curPos>0.17 && curPos<0.20 && power_ratio > 0.6 && fuel_ratio > 0)  {
    changeRocketImgExplosion()
    setTimeout(() => {alert("Explosion ! Trop de puissance au point max Q !")}, 1000);
  }
  else if (curPos >= 1) {
    if (curStage == 4 || curStage == 3) {
      alert("Mission réussi ! Le 3e étage est en orbite ! Bravo !")
      if (!manual_enabled) {
        alert("Le code de cette mission est 1957")
      }
    } else {
      alert("Vous avez atteint la bonne hauteur mais pas avec le bon étage ou sans avoir largué la tour de sauvetage !")
    }
  } else {
    simu_timeouts.push(setTimeout(function() {stepSimulation(t)}, 40))
  }
}

function changeRocketImg(curStage) {
 let p = 'img/r' + curStage +'.png';
 rocket_img.load(p)
 rocket.load(p)
}
function changeRocketImgExplosion() {
  rocket_img.load('img/explosion.png')
  rocket.load('img/explosion.png')
 }

