/* 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";
  }
}





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





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

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/r1.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/r1.png').attr({x: 550, y : 0})

function enableManual() {
  manual_enabled = true;
  document.addEventListener('keydown', function(event) {
      if(event.keyCode == 38) {
          changePower(power_ratio+0.01)
      }
      else if(event.keyCode == 40) {
          changePower(power_ratio-0.01)
      } else if (event.keyCode == 32) {
        if (rocketLaunched) changeRocketStage()
        else launchRocket()
      }
  });
}



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()
  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/r1.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/r1.png').attr({x: 550, y : 0})
  changeFuel(1, 0)
  changePower(0, 0)
  stepSimulation(getCurTime())
}

function launchRocket() {
  rocketLaunched = true;
}

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

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

}

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

}

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

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

function isInMaxQ() {
  return curPos>0.14 && curPos<0.23
}

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)  {
    changeRocketImg('img/explosion.png')
    alert("Explosion ! Trop de puissance au point max Q !")
  }
  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 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);
}

function changeRocketImg(imgPath) {
 rocket_img.load(imgPath)
 rocket.load(imgPath)
}



function changeRocketStage() {
  curStage = (curStage < 4)?(curStage+1):4;
  changeRocketImg('img/r' + curStage +'.png')
  if (curStage < 4) changeFuel(1, 200)
}
