var jsPsychPictureChoice = (function (jspsych) {
  "use strict";

  const info = {
    name: "picture-choice",
    parameters: {
      /** The question/word/phrase to be displayed */
      question: {
          type: jspsych.ParameterType.STRING,
          pretty_name: 'Question',
          default: null
        },
      /** The correct image to be displayed */
      stimulus: {
        type: jspsych.ParameterType.IMAGE,
        pretty_name: 'Stimulus',
        default: undefined,
      },
      /** The foil image to be displayed */
      foil: {
        type: jspsych.ParameterType.IMAGE,
        pretty_name: 'Foil',
        default: undefined,
      },
      /** The expected choice number */
      expected_choice:{
        type: jspsych.ParameterType.INT,
        pretty_name: 'Expected choice',
        default: 1,
      },
      /** The prompt to be displayed */
      prompt: {
        type: jspsych.ParameterType.STRING,
        pretty_name: 'Sentence',
        default: null      },
      /** The trial duration */
      trial_duration: {
        type: jspsych.ParameterType.INT,
        pretty_name: 'Trial duration',
        default: null      },
      /** Does a response end the trial? */
      response_ends_trial: {
        type: jspsych.ParameterType.BOOL,
        pretty_name: 'Response ends trial',
        default: true      },
      /** Is feedback provided? */
      feedback:{
        type: jspsych.ParameterType.BOOL,
        pretty_name: 'Show feedback',
        default: false      },
      /** The duration of the feedback */
      feedback_duration: {
        type: jspsych.ParameterType.INT,
        pretty_name: 'Feedback duration',
        default: 500      }
    },
  };

  /**
   * **picture-choice**
   *
   * choice between two pictures displayed as buttons
   *
   * @author MORA & JENNY
   * @see {@link https://DOCUMENTATION_URL DOCUMENTATION LINK TEXT}
   */
  class PictureMatchPlugin {
    constructor(jsPsych) {
      this.jsPsych = jsPsych;
    }
    trial(display_element, trial) {
      if (trial.expected_choice==0){
        var image0 = trial.stimulus;
        var image1 = trial.foil;
      }
      else {
        var image0 = trial.foil;
        var image1 = trial.stimulus;
      }
      // console.log("correct: "+trial.stimulus)
      // console.log("button number: "+trial.expected_choice)
      
      // display stimulus
      var html = '<div class="row">';

      // first image
      html += '<input type="image"  class="image" alt="'+ image0 +'"'+ 'src="'+image0+'" id="image0"';
      html +='"></input>'

      // second image
      html += '<input type="image" class="image" alt="'+ image1 +'"'+ 'src="'+image1+'" id="image1"';
      html +='"></input>'; //close image and row

      html += '</div>';// close row

      //show prompt if there is one
      if (trial.prompt !== null) {
        html += '<p style="font-size:25px">' + trial.prompt + '</p>' ;
      }

      display_element.innerHTML = html;

      // listen to images
      var start_time = performance.now();

      function whattodo(e){
        var choice = e.currentTarget.getAttribute('id'); // don't use dataset for jsdom compatibility
        after_response(choice);
      }
      display_element.querySelector('#image0').addEventListener('click', whattodo);
      display_element.querySelector('#image1').addEventListener('click', whattodo);

      // store response
      var response = {
        rt: null,
        button: null,
        image: null,
      };

      // feedback function
      function feedback(expected_choice, response){
        var add_time = 0;
        var incorrect = expected_choice==1 ? 0 : 1;

        if (response== "image"+incorrect){
          document.getElementById('image'+incorrect).style.borderColor='#b80F0A';
          document.getElementById('image'+incorrect).style.backgroundColor='#b80F0A';
          document.getElementById('image'+incorrect).style.borderWidth = '5px';
          add_time = +2000;
        }

        else if (response!="image"+incorrect) {
          document.getElementById('image'+expected_choice).style.borderColor='#2E8B57';
          document.getElementById('image'+expected_choice).style.backgroundColor='#2E8B57';
          document.getElementById('image'+expected_choice).style.borderWidth = '5px';
        }
        return add_time;
      }

      // function to handle responses by the subject
      function after_response(choice) {

        // measure rt
        var end_time = performance.now();
        var rt = end_time - start_time;
        response.button = choice.slice(5); // e.g., change image0 to 0
        response.rt = rt;
        response.image = document.getElementById(choice).src;

        // disable all the buttons after a response
        var btns = document.querySelectorAll('.image');
        for(var i=0; i< btns.length; i++){
          btns[i].removeEventListener('click', whattodo);
          btns[i].setAttribute('disabled', 'disabled');
        }

        if (trial.response_ends_trial) {
          if (trial.feedback){
            var add_time= feedback(trial.expected_choice, choice);
            setTimeout(function(){
              end_trial();}, trial.feedback_duration+add_time) }
          else {
            setTimeout(function() {
              end_trial();
            }, 1000);
          }
        }

      };

      // function to end trial when it is time
      const end_trial = () => {

        // kill any remaining setTimeout handlers
        this.jsPsych.pluginAPI.clearAllTimeouts();

        // gather the data to store for the trial
        var trial_data = {
          "rt": response.rt,
          "stimulus": trial.stimulus,
          "image_chosen": response.image,
          "button_pressed": response.button
        };

        // clear the display
        display_element.innerHTML = '';

        // move on to the next trial
        this.jsPsych.finishTrial(trial_data);
      };

      // end trial if time limit is set
      if (trial.trial_duration !== null) {
        jsPsych.pluginAPI.setTimeout(function() {
          end_trial();
        }, trial.trial_duration);
      }
    } // end trial
  }
  PictureMatchPlugin.info = info;

  return PictureMatchPlugin;
})(jsPsychModule);

