let treemap_labels = [];
let treemap_parents = [];
let treemap_values = [];
let treemap_colors = [];

let front_parameters = {};
let exploration_strategy = "whole_data";


const SPLIT_BY_MONETARY_VALUE = true;
const AVAILABLE_MONETARY_VALUES = [5, 4, 3, 2, 1];

const WHOLE_DATA_TREEMAP_CHART = "whole_data_treemap_chart";
const MONETARY_VALUE_RELATIVE_IMPORTANCE_TREEMAP_CHART = "monetary_value_relative_importance_treemap_chart";
const MONETARY_VALUE_TREEMAP_CHARTS = ["monetary_value_5_treemap_chart", "monetary_value_4_treemap_chart", "monetary_value_3_treemap_chart", "monetary_value_2_treemap_chart", "monetary_value_1_treemap_chart"];
const DEFAULT_FRONT_PARAMETERS = {
    "exploration_strategy": exploration_strategy,
    "available_monetary_values": AVAILABLE_MONETARY_VALUES,
    "rfm_datasource":"reference_period_cutomers"}

// Divs :
rfm_datasource_selector_container = document.getElementById("rfm_datasource_selector_container");
whole_data_treemap_container = document.getElementById("whole_data_treemap_container");
monetary_value_relative_importance_treemap_container = document.getElementById("monetary_value_relative_importance_treemap_container");
split_by_monetary_value_treemap_container = document.getElementById("split_by_monetary_value_treemap_container");


function clearDocumentElementsById(list_of_element_ids){
    list_of_element_ids.forEach(function(item, index) {
        document_element = document.getElementById(item);
        document_element.innerHTML = "";
    });
};


function prepareDataForTreemap(treemap_data){
    treemap_labels = treemap_data["labels"]
    treemap_parents = treemap_data["parents"]
    treemap_values = treemap_data["values"]
    treemap_colors = treemap_data["colors"]
    treemap_parameters = [{
        "type": 'treemap',
        "labels": treemap_labels,
        "parents": treemap_parents,
        "values": treemap_values,
        "marker": {"colors": treemap_colors},
        "branchvalues": "total",
        "textfont": {"color": "#FFFFFF"}
    }]
    return treemap_parameters;    
};


function loadFrontParameters(){
    exploration_strategy = getSelectValues(exploration_strategy_selector)[0];
    rfm_datasource = getSelectValues(rfm_datasource_selector)[0];
    console.log(`Selected treemap exploration strategy is : ${exploration_strategy}`);
    front_parameters = {
        "exploration_strategy": exploration_strategy,
        "available_monetary_values": AVAILABLE_MONETARY_VALUES,
        "rfm_datasource": rfm_datasource
    }
    $.ajax({
        type: "POST",
        method: "POST",
        url: getWebAppBackendUrl('send_app_features')+'/',
        data: JSON.stringify(front_parameters),
        dataType:"json",
        success: function(backend_response){
            
            console.log(`Computing charts with exploration strategy : '${exploration_strategy}'`)
            propagate_rfm = backend_response["propagate_rfm"];
            if (propagate_rfm==true){
                rfm_datasource_selector_container.style.display = "block";
            }
            else {
                rfm_datasource_selector_container.style.display = "none";
            }
            treemaps_data = backend_response["data"];
            if (exploration_strategy == "whole_data") {
                whole_data_treemap_container.style.display = "block";
                monetary_value_relative_importance_treemap_container.style.display = "none";
                split_by_monetary_value_treemap_container.style.display = "none";
                clearDocumentElementsById([MONETARY_VALUE_RELATIVE_IMPORTANCE_TREEMAP_CHART]);
                clearDocumentElementsById(MONETARY_VALUE_TREEMAP_CHARTS);
                treemaps_data.forEach(function(item, index) {
                    treemap_parameters = prepareDataForTreemap(item);
                    treemap_div = 'whole_data_treemap_chart';
                    Plotly.newPlot(treemap_div, treemap_parameters);
                });
            }
            
            else if (exploration_strategy == "monetary_value_relative_importance"){
                whole_data_treemap_container.style.display = "none";
                monetary_value_relative_importance_treemap_container.style.display = "block";
                split_by_monetary_value_treemap_container.style.display = "none";
                clearDocumentElementsById([WHOLE_DATA_TREEMAP_CHART]);
                clearDocumentElementsById(MONETARY_VALUE_TREEMAP_CHARTS);
                treemaps_data.forEach(function(item, index) {
                    treemap_parameters = prepareDataForTreemap(item);
                    treemap_div = 'monetary_value_relative_importance_treemap_chart';
                    Plotly.newPlot(treemap_div, treemap_parameters);
                });
            }
            
            else if (exploration_strategy == "split_by_monetary_value"){
                treemaps_data.forEach(function(item, index) {
                    whole_data_treemap_container.style.display = "none";
                monetary_value_relative_importance_treemap_container.style.display = "none";
                split_by_monetary_value_treemap_container.style.display = "block";
                clearDocumentElementsById([WHOLE_DATA_TREEMAP_CHART]);
                clearDocumentElementsById([MONETARY_VALUE_RELATIVE_IMPORTANCE_TREEMAP_CHART]);
                    treemap_parameters = prepareDataForTreemap(item)
                    monetary_value_treemap_id = AVAILABLE_MONETARY_VALUES[index];
                    treemap_div_id = `monetary_value_${monetary_value_treemap_id}_treemap_chart`;
                    Plotly.newPlot(treemap_div_id, treemap_parameters);
                });
            };
  
    }});
}



/*HELPERS HEADER | START*/

let collapsible_elements = document.getElementsByClassName("collapsible");
let i;

for (i = 0; i < collapsible_elements.length; i++) {
  collapsible_elements[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var content = this.nextElementSibling;
    if (content.style.display === "block") {
      content.style.display = "none";
    } else {
      content.style.display = "block";
    }
  });
}

let application_title_button = document.getElementById("application_title_button");
let app_presentation_container = document.getElementById("app_presentation_container");
let app_helpers_containers = document.getElementById("app_helpers_containers");

function LoadHelpers(){
    application_title_button.className = "collapsible active";
    app_presentation_container.style.display = "block";
    app_helpers_containers.style.display = "none";
}

LoadHelpers();
/*HELPERS HEADER | END*/


/* SELECT & MULTISELECT | START */


// Select : 
let exploration_strategy_selector = document.getElementById("exploration_strategy_selector");
let rfm_datasource_selector = document.getElementById("rfm_datasource_selector");

//Multiselect :
let monetary_value_treemaps_selector = document.getElementById("monetary_value_treemaps_selector");

// Functions :
function getSelectValues(select) {
  let result = [];
  let options = select && select.options;
  let opt;

  for (let i=0, iLen=options.length; i<iLen; i++) {
    opt = options[i];
    if (opt.selected) {
      result.push(opt.value || opt.text);
    }
  }
  return result;
};


// Events :
exploration_strategy_selector.onchange = function(){    
    loadFrontParameters();
};
rfm_datasource_selector.onchange = function(){    
    loadFrontParameters();
};

function updateDisplayedMonetaryValueTreemaps() {
    monetary_value_treemaps_ids_to_display = getSelectValues(monetary_value_treemaps_selector);
    console.log(`Selected monetary values are : ${monetary_value_treemaps_ids_to_display}`);
    console.log(`AVAILABLE_MONETARY_VALUES are : ${AVAILABLE_MONETARY_VALUES}`)
    AVAILABLE_MONETARY_VALUES.forEach(function(item, index) {
        treemap_div_id = `monetary_value_${item}_treemap_chart`;
        display_monetary_value_treemap = monetary_value_treemaps_ids_to_display.includes(String(item));
        if (display_monetary_value_treemap){
            document.getElementById(treemap_div_id).style.display = "block";
        }
        else {
            document.getElementById(treemap_div_id).style.display = "none";
        };
    });
};

monetary_value_treemaps_selector.onchange = function(){
    updateDisplayedMonetaryValueTreemaps()
};


// UI dropdown : 
$('.dropdown').dropdown({
  label: {
    duration: 0,
  },
  debug: true,
  performance: true,
});

/* SELECT & MULTISELECT | END */

//loadFrontParameters(DEFAULT_FRONT_PARAMETERS)
loadFrontParameters();
