function Abort()
{
   throw new Error('This is not an error. This is just to abort javascript');
}

function run() {
    const console = document.getElementById("console");
    const runner = new BrythonRunner({
      stdout: {
        write(content) {
          console.innerHTML += content;
          console.scrollTop = console.scrollHeight;
        },
        flush() {}
      },
      stderr: {
        write(content) {
          console.innerHTML += content;
          console.scrollTop = console.scrollHeight;
        },
        flush() {}
      },
      stdin: {
        async readline() {
          console.innerHTML += "\n";
          console.scrollTop = console.scrollHeight;
          var userInput = prompt();
          return userInput;
        },
        flush() {}
      }
     });
    var code = editor.getValue();
    runner.runCode(code)
    }
          
function run_init() {        
  if (document.getElementById("console") != '') {
    document.getElementById("console").innerHTML = '';
    run();
    //setTimeout(() => {console.log("Resolve while pb")}, 1000);
    //setTimeout(() => {Abort()}, 5000);
  } 
  else {
    run();
    //setTimeout(() => {console.log("Resolve while pb")}, 1000);
    //setTimeout(() => {Abort()}, 5000);
  }
}

var editor = ace.edit("editor");
editor.setTheme("ace/theme/vibrant_ink");
editor.getSession().setMode("ace/mode/python");
editor.setFontSize("16px");
editor.container.style.height = "250px"
editor.setOptions({
  enableLiveAutocompletion: true,
  copyWithEmptySelection: true,
  showGutter: true,
  useWrapMode: true, // wrap text to view
  indentedSoftWrap: false,
});

//Function that execute given code and return the result in a given element by id
        
function exec(code, id) {
  const terminal = document.getElementById("console");
  const retour = document.getElementById(id);
  const runner = new BrythonRunner({
    stdout: {
      write(content) {
        if (id == "code"){
          retourCode = content;
        }
        if (id == "solution"){
          retourSolution = content;
        }
      },
      flush() {}
    },
    stderr: {
      write(content) {
        if (id == "solution"){
          retourSolution = "ERROR";
        }
        terminal.innerHTML += content;
        terminal.scrollTop = terminal.scrollHeight;
      },
      flush() {}
    },
    stdin: {
      async readline() {
        terminal.innerHTML += "\n";
        terminal.scrollTop = terminal.scrollHeight;
        var userInput = prompt();
        return userInput;
      },
      flush() {}
    }
  });
  runner.runCode(code)
}
          
//~ Function that check if the code in the editor as the same result as the solution.
          
function check(){
  if (retourSolution == "ERROR") {
    result.innerHTML = "Il semblerait qu'il y a une erreur dans ton code :/";
    result.classList.remove('hidden');
  }

  else if (retourSolution == retourCode) {
    result.innerHTML = "Bien joué";
    result.classList.remove('hidden');
  } 
  else {
    result.innerHTML = "Mauvaise réponse";
    result.classList.remove('hidden');
  }
}
		
//~ Function that test the user code
          
async function submit(){
  var test = editor.getValue()+`\n
import random as r
def estPalindromeVerif(var):
  if(var == var[::-1]):
      return True
  else:
      return False

def testPalindrome(x):
  l=[1,2,3,2,1]
  if(estPalindrome(l)==False):
    return False
  l=[9,5,7,7,9]
  if(estPalindrome(l)==True):
    return False
  l=[]
  for i in range(x):
    for j in range(r.randint(1,10)):
      l.append(r.randint(0,9))
    if(estPalindromeVerif(l)!=estPalindrome(l)):
      return False
    l=[]
  return True

print(testPalindrome(5))
  `;
  exec("print ('True')", "code"); 
  exec(test, "solution");
  await new Promise(r => setTimeout(r, 1500));
  check();
}
       
function aide(){
  if(document.getElementById("textAide").textContent == ""){
    document.getElementById("textAide").textContent = "En python l’instruction [::-1] permet d’inverse une chaine de caractère. Par exemple print(\"ae\"[::-1])  affiche : ea.";  
  }
  else{
    document.getElementById("textAide").textContent = "";
  }
}

function rappel(){
  if(document.getElementById("textRappel").textContent == ""){
    document.getElementById("textRappel").textContent = "Un palindrome est un nombre qui peut se lire dans les deux sens. Par exemple 111.";  
  }
  else{
    document.getElementById("textRappel").textContent = "";
  }
}

