import {SemanticAnalyser} from './../processor/semantic/semanticAnalyser';
import {IVProgProcessor} from './../processor/ivprogProcessor';
import { InputTest } from './inputTest';
import { OutputTest } from './outputTest';
import { LocalizedStrings } from './../services/localizedStringsService'

export function autoGenerateTestCaseOutput (program_text, testCases) {
  let copyTestCases = testCases.map((test) => Object.assign({}, test));
  try {
    const program = SemanticAnalyser.analyseFromSource(program_text);
    const resultList = testCases.map((test, id) => {
      const input = new InputTest(test.input);
      const output = new OutputTest();
      const exec =  new IVProgProcessor(program);
      exec.registerInput(input);
      exec.registerOutput(output);
      return exec.interpretAST().then(_ => {
        return {id: id, program: exec};
      });
    });
    return Promise.all(resultList).then(result_final => {
      for(let i = 0; i < result_final.length; ++i) {
        const result = result_final[i];
        const output = result.program.output.list;
        const input = result.program.input;
        if(input.index != input.inputList.length) {
          window.showAlert(LocalizedStrings.getMessage("testcase_autogen_unused_input", [result.id+1]));
          return Promise.resolve(false);
        }
        if(output.length == 0) {
          window.showAlert(LocalizedStrings.getMessage("testcase_autogen_empty", [result.id+1]));
        }
        copyTestCases[result.id].output = output;
      }
      window.outputGenerated(copyTestCases);
      return Promise.resolve(true);
    });
  }catch (error) {
    return Promise.reject(error)
  }
}