

var DEBUG = true;
if (!DEBUG) {
  if (!window.console) window.console = {};
  var methods = ["log", "debug", "warn", "info"];
  for (var i = 0; i < methods.length; i++) {
    console[methods[i]] = function () { };
  }
}


const NB_DIGITS_FOR_TIME = 6;

var scene_directory = "material_probe_2";
var scene_name = "material_probe";


var nb_values_per_parameters; // This is an array for each paremter we have the number of its possible values

var parameter_values = new Map( [ 
  [0, new Array("1 BG No LUT", "1 BG LUT", "TWA")], 
  [1, new Array(0.01, 0.05, 0.1) ],
  [2, new Array(0.08, 0.12, 0.16, 0.2)],
  [3, new Array(300, 375, 450, 525, 600, 675)] ,
]  );

var parameter_name_to_index = new Map( [
  ["Model", 0],
  ["Alpha_S",1],
  ["Anisotropy", 2],
  ["Pitch",     3 ],
]);

var parameter_names;  // Array with all parameter names deduced from the Map paramter_name_to_index
// =  new Array("Model", "Alpha_S", "Anisotropy", "Pitch");

var json_parameter_names = new Array();

var current_indexes_per_column = new Array(
  new Array(0, 0, 0, 0),
  new Array(0, 0, 0, 0),
  new Array(0, 0, 0, 0),
);


// parameter_values is a Map
function init_number_of_values_per_parameter(parameter_values)
{
  console.log(" parameter_values.size = " + parameter_values.size)
  var nb_values_per_parameters = Array(parameter_values.size);

  for (let i = 0; i < parameter_values.size; i++)
  {
    console.log(parameter_values.get(i).length);
    nb_values_per_parameters[i] = parameter_values.get(i).length;
  }

  return nb_values_per_parameters;
}

function  number_of_rendered_images() 
{
  var nb = 1;
  console.log(console.log(parameter_values.size));
  for( let i=0; i < parameter_values.size; i++)
  {
    nb *= parameter_values.get(i).length;
  }
  return nb;
}

//must be an array of size "Number of parameters" 
function image_number_from_parameter_indexes(parameters_indexes, nb_values_per_parameters )
{
  var index = parameters_indexes[0] * nb_values_per_parameters[1] * nb_values_per_parameters[2] * nb_values_per_parameters[3];
  index    += parameters_indexes[1] * nb_values_per_parameters[2] * nb_values_per_parameters[3];
  index    += parameters_indexes[2] * nb_values_per_parameters[3];
  index    += parameters_indexes[3];

  return index;
}



function reportWindowSize() {

  // TODO : Use Ratio of the original image to maintain it ?
  var ratio = window.innerWidth / window.innerHeight;
  var image_width = (window.innerWidth / 3.5);

  document.getElementById("image_selector_0").style.width = image_width;
  document.getElementById("image_selector_1").style.width = image_width;
  document.getElementById("image_selector_2").style.width = image_width;
 
  var image_height = image_width / ratio;

  document.getElementById("image_selector_0").style.height = image_height;
  document.getElementById("image_selector_1").style.height = image_height;
  document.getElementById("image_selector_2").style.height = image_height;


}

function init_parameter_names(parameter_name_to_index)
{
  parameter_names = new Array( parameter_name_to_index.size);

  const mapIter = parameter_name_to_index.keys();
  for (let i = 0; i < parameter_name_to_index.size; i++)
  {
    parameter_names[i] = mapIter.next().value;
  }

  return parameter_names;
}

function image_filename_from_index(image_index, nb_of_r_images) {
  var number_of_digit_for_rendered_images = nb_of_r_images.toString().length + 1;
  var number_of_zero_before_image_index = number_of_digit_for_rendered_images - image_index.toString().length
  var str_padding = '0'.repeat(number_of_zero_before_image_index);

  var filename = scene_directory + "/" + scene_name + "_" + str_padding + image_index.toString() + ".png";

  return filename;
}

function get_param_name_and_column_idx_from_id(the_id_as_string) {
  console.log(the_id_as_string);
  var pos_underline = the_id_as_string.lastIndexOf("_");
  return [the_id_as_string.substr(0, pos_underline), the_id_as_string.substr(pos_underline + 1, the_id_as_string.length)]
}



function selectorChanged(event) {
  console.log(" selectorCHanged ");
  console.log(event);
  console.log(this.id);
  console.log(this.value);

  // c_idx = column_number  
  var param_name_c_idx = get_param_name_and_column_idx_from_id(this.id);
  var current_param_name = param_name_c_idx[0];
  var current_col_idx = param_name_c_idx[1];

  console.log(param_name_c_idx);

  var image_selector_id = "image_selector_" + current_col_idx.toString();
  console.log(image_selector_id);

  var parameter_index = parameter_name_to_index.get(current_param_name);

  console.log(" current_indexes_per_column[idx] = " + current_indexes_per_column[current_col_idx]);

  current_indexes_per_column[current_col_idx][parameter_index] = parseInt(this.value);

  var  new_image_index = image_number_from_parameter_indexes(current_indexes_per_column[current_col_idx], nb_values_per_parameters)
  console.log("new_image_index = " + new_image_index);

  var image_filename = image_filename_from_index(new_image_index, number_of_rendered_images());
  console.log(image_filename);
  document.getElementById(image_selector_id).setAttribute("src", image_filename);

  var execution_time_id = "execution_time_" + current_col_idx.toString();
  const exec_time = parseFloat(json[new_image_index.toString()]["malia_execution_time"]);

  const exec_time_as_str = Number.parseFloat(exec_time).toFixed(NB_DIGITS_FOR_TIME) + " seconds";
  
  document.getElementById(execution_time_id).innerHTML = exec_time_as_str;

}

function loadUI() 
{

  console.log("inside load UI");
  
  
  //loadJson(); 
  
  console.log(scene_name);


  nb_values_per_parameters = init_number_of_values_per_parameter(parameter_values);

  console.log("nb value parameters 0 = " + nb_values_per_parameters[0]); 
  console.log(parameter_values);

  
  parameter_names = init_parameter_names( parameter_name_to_index);
  console.log(parameter_names);
  
  for( let i=0; i < parameter_names.length; i++) {
    let id_str = "param_name_" + i;
    document.getElementById(id_str).innerHTML = parameter_names[i];

    let index_parameter = parameter_name_to_index.get(parameter_names[i]);
    let number_of_values_for_parameter = parameter_values.get(index_parameter).length;
    console.log("index_parameter" + index_parameter + "  number_of_val for parameter = " + number_of_values_for_parameter);
    

    for( let col_number=0; col_number < 3; col_number++) { 
      var id_string_select = parameter_names[i] + "_" + col_number;
      console.log(id_string_select);
      var select_element = document.getElementById(id_string_select);
      select_element.addEventListener("change", selectorChanged)
      for( let k=0; k < number_of_values_for_parameter; k++) {
        var opt = document.createElement('option');
        opt.value = k;
        opt.innerHTML = parameter_values.get(index_parameter)[k];
        select_element.appendChild(opt);
      }//end-for-loop-k
    }// end-for-loop col_number

  }

  //Initial Images 
  var str_padding = '0'.repeat( (number_of_rendered_images()).toString().length+1 );
  document.getElementById("image_selector_0").setAttribute("src", scene_directory + "/" + scene_name + "_" + str_padding + ".png");
  document.getElementById("image_selector_1").setAttribute("src", scene_directory + "/" + scene_name + "_" + str_padding + ".png");
  document.getElementById("image_selector_2").setAttribute("src", scene_directory + "/" + scene_name + "_" + str_padding + ".png");


  document.getElementById("execution_time_0").innerHTML = parseFloat(json["0"]["malia_execution_time"]).toFixed(NB_DIGITS_FOR_TIME) + " s.";
  document.getElementById("execution_time_1").innerHTML = parseFloat(json["0"]["malia_execution_time"]).toFixed(NB_DIGITS_FOR_TIME) + " s.";
  document.getElementById("execution_time_2").innerHTML = parseFloat(json["0"]["malia_execution_time"]).toFixed(NB_DIGITS_FOR_TIME) + " s.";


  //
  var image_width = (window.innerWidth / 3.5);

  document.getElementById("image_selector_0").style.width = image_width;
  document.getElementById("image_selector_1").style.width = image_width;
  document.getElementById("image_selector_2").style.width = image_width;


  var image_height = (window.innerHeight / 3.5);

  document.getElementById("image_selector_0").style.height = image_height;
  document.getElementById("image_selector_1").style.height = image_height;
  document.getElementById("image_selector_2").style.height = image_height;

  window.onresize = reportWindowSize;

  
  
}




const response = await fetch("material_probe_2/material_probe.json");
const json = await response.json();
console.log(json["0"]);
console.log(json["0"]["malia_execution_time"]);
console.log("##########################")
var params_from_json = json["parameters"];

var fixed_parameter_names = new Array(); 
console.log(params_from_json);

for( const x in params_from_json) {
  if (params_from_json[x].length > 1)
  {
    json_parameter_names.push(x);
  }
  else
  {
    fixed_parameter_names.push(x);
  }
}
console.log("##########################")
console.log(json_parameter_names);
console.log("##########################")
console.log(fixed_parameter_names);
console.log("##########################")
// We need to fetch from the JSOn file all the data to populate the different variables


switch (document.readyState) {
  case "loading":
    // The document is loading.
    console.log("DOCUMENT IS LOADING ");
    break;
  case "interactive": {
    // The document has finished loading and we can access DOM elements.
    // Sub-resources such as scripts, images, stylesheets and frames are still loading.
    console.log("DOM available scripts images stylesheets and frames are loading");
    // const span = document.createElement("span");
    // span.textContent = "A <span> element.";
    // document.body.appendChild(span);
    break;
  }
  case "complete":
    {
      // The page is fully loaded.
      //We modify the user interface 
      loadUI();
      break;
    }
  
}
