// App variables : 
let compute_refined_rules = false;
let some_items_selected = false;
let n_matching_items = document.getElementById("n_matching_items");
let n_items_to_analyze = 0;
let selected_items = [];
let some_scopes_selected = false;
let selected_rule_scopes = [];
let filter_on_common_items = false;
let common_scope_value = 0;

let items_to_display = [];
let charts_data = [];
let matching_items_message = "";
let available_items = [];

let bar_chart_data = {};


// Divs :
let rule_sope_button = document.getElementById("rule_sope_helper_button");
let rule_sope_helper_container = document.getElementById("rule_sope_helper_container");
let max_frequent_items_to_analyze_container = document.getElementById("max_frequent_items_to_analyze_container");

// Sliders : 
let items_to_analyze_slider = document.getElementById("items_to_analyze_slider");
let items_to_analyze_value = document.getElementById("items_to_analyze_value");
items_to_analyze_value.innerHTML = items_to_analyze_slider.value;
items_to_analyze_slider.oninput = function() {
  items_to_analyze_value.innerHTML = this.value;
}


// Multiselects : 
let rules_scope_selector = document.getElementById("rules_scope_selector");
let items_selector = document.getElementById("items_selector");
// Table :
let association_rules_table = document.getElementById("association_rules_table")

// Input :
let common_scope_input = document.getElementById("common_scope_input")

// Containers :
let canvas_container = document.getElementById("canvas_container");
let common_scope_container = document.getElementById("common_scope_container");
common_scope_container.style.display = "none";
let items_focus_container = document.getElementById("items_focus_container");
items_focus_container.style.display = "none";
let items_focus_switch_container = document.getElementById("items_focus_switch_container");
let common_scope_value_container = document.getElementById("common_scope_value_container");
let common_items_switch_container = document.getElementById("common_items_switch_container");
let items_container = document.getElementById("items_container");
items_container.style.display = "none";


// Events :
rules_scope_selector.onchange = function(){
    selected_rule_scopes = getSelectValues(rules_scope_selector)
    some_scopes_selected = listIsNotEmpty(selected_rule_scopes);
    n_selected_rules_scope = selected_rule_scopes.length;
    if (n_selected_rules_scope >= 2){
        common_scope_container.style.display = "block";
        RefreshCommonScopeElements()
    }
    else {
        common_scope_container.style.display = "none";
        let checkbox = GetCheckbox("common_items_switch_checkbox")
        checkbox.checked = false
        RefreshCommonScopeElements()
    };
    
    if (n_selected_rules_scope >= 1){
        items_focus_container.style.display = "block";
        max_frequent_items_to_analyze_container.style.display = "block";
        items_to_analyze_slider.style.display = "block";
        
    }
    else {
        cleanBarChartContainer()
        items_focus_container.style.display = "none";
        max_frequent_items_to_analyze_container.style.display = "none";
        items_to_analyze_slider.style.display = "none";
    };
    
    if (some_scopes_selected){
        refreshFrontVariablesThenPageRender();
    }
    else {
        n_matching_items.innerHTML = "";
    }
    
};

items_selector.onchange = function(){
    refreshFrontVariablesThenPageRender();
};

items_to_analyze_slider.onchange = function(){
    refreshFrontVariablesThenPageRender();
};

common_items_switch_container.onchange = function(){
    RefreshCommonScopeElements();
    refreshFrontVariablesThenPageRender();
};

common_scope_input.onchange = function(){
    refreshFrontVariablesThenPageRender();
};

items_focus_switch_container.onchange = function(){
    display_items_of_interest_filter = CheckboxIsActivated("items_focus_switch_checkbox");
    if (display_items_of_interest_filter){
        items_container.style.display = "block";
    }
    else {
        items_container.style.display = "none";
        refreshAvailableItems()
    }
    refreshFrontVariablesThenPageRender();
};

function RefreshCommonScopeElements(){
    
    if (!CheckboxIsActivated("common_items_switch_checkbox")){
        
        common_scope_value_container.style.display = "none";
    }
    else{
        common_scope_value_container.style.display = "block";
    };
};

function GetCheckbox(checkbox_id){
    return document.getElementById(checkbox_id);
};

function CheckboxIsActivated(checkbox_id){
    let checkbox = GetCheckbox(checkbox_id);
    return checkbox.checked;
}


function cleanBarChartContainer() {
    console.log("Cleaning bar chart container")
    canvas_container.innerHTML = '<canvas id="canvas"></canvas>'
}

function initializeFrontendParameters(){
    RefreshCommonScopeElements()
    $.getJSON(getWebAppBackendUrl('initialize_frontend_parameters'+'/'),
        function(backend_response){
        rules_scopes = backend_response["rules_scopes"];
        compute_refined_rules = backend_response["compute_refined_rules"];
        application_items = backend_response["application_items"];
        enrich_html_select(application_items, "items_selector", "option");
        if (compute_refined_rules) {
            enrich_html_select(rules_scopes, "rules_scope_selector", "option");
            max_frequent_items_to_analyze_container.style.display = "none";
            items_to_analyze_slider.style.display = "none";
        }
        
        else {
            items_focus_container.style.display = "block";            
            rules_scope_container.style.display = "none";
            common_scope_container.style.display = "none";
            rule_sope_button.style.display = "none";
            rule_sope_helper_container.style.display = "none";
        }        
    })}

function enrich_html_select(list_of_options, html_parent_id, child_html_type){
    console.log(`Enriching HTML element '${html_parent_id}'`);
    let html_element = document.getElementById(html_parent_id)
    list_of_options.forEach(function(item, index) {
        let option = document.createElement(child_html_type);
        option.text = `${item}`;
        html_element.add(option);
    });
}

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;
};

function refreshFrontVariablesThenPageRender() {
    console.log(`Refreshing front variables ...`);
    n_items_to_analyze = items_to_analyze_slider.value;
    selected_items = getSelectValues(items_selector);
    some_items_selected = listIsNotEmpty(selected_items);
    selected_rule_scopes = getSelectValues(rules_scope_selector);
    some_scopes_selected = listIsNotEmpty(selected_rule_scopes);
    filter_on_common_items = CheckboxIsActivated("common_items_switch_checkbox");
    common_scope_value = common_scope_input.value;
    filtering_parameters = {"some_items_selected": some_items_selected, "selected_items": selected_items,
                            "some_scopes_selected": some_scopes_selected, "selected_rule_scopes": selected_rule_scopes,
                            "n_items_to_analyze": n_items_to_analyze, "filter_on_common_items": filter_on_common_items,
                            "common_scope_value": common_scope_value
                           };
    console.log(`filtering_parameters : ${JSON.stringify(filtering_parameters)}`);    
    $.when($.ajax({
        type: "POST",
        method: "POST",
        url: getWebAppBackendUrl('refresh_bar_chart_data')+'/',
        data: JSON.stringify(filtering_parameters),
        dataType:"json",
        success: function(backend_response){
            console.log(`Received data from backend`);
            items_to_display = backend_response["items_to_display"];
            charts_data = backend_response["charts_data"];
            matching_items_message = backend_response["matching_items_message"];
            available_items = backend_response["available_items"];
        }})).then(refreshPageRender);
};

function refreshBarChart(){
    console.log(`Refreshing bar chart data ...`);
    const chart_options = {
        legend: {
            display: true,
            position: 'top',
            labels: {
                fontColor: "#333333",
            }
        },
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true
            }
          }]
        }
    };
    bar_chart_data = {
        labels: items_to_display,
        datasets: charts_data
    };
    cleanBarChartContainer()
    console.log(`Bar chart cleaned !`);
    let ctx = document.getElementById("canvas").getContext("2d");
    let bar_chart = new Chart(ctx, {type: 'bar', data: bar_chart_data, options: chart_options});
    console.log(`Bar chart updated !`);
};

function refreshAvailableItems(){
    console.log(`Refreshing available items ...`)
    if (!some_items_selected) {
        items_selector.innerHTML = "";
        enrich_html_select(available_items, "items_selector", "option");
    }
};

function refreshMatchingItemsMessage(){
    console.log(`Refreshing matching_items_message with : ${matching_items_message}`);
    n_matching_items.innerHTML = matching_items_message;
}

function refreshPageRender(){
    console.log(`Refreshing page render with parameters {"compute_refined_rules": ${compute_refined_rules}, "some_scopes_selected": ${some_scopes_selected}}`);
    if (compute_refined_rules) {
        if (some_scopes_selected){
            refreshBarChart();
            refreshAvailableItems();
            refreshMatchingItemsMessage();
        }
        else {
            cleanBarChartContainer();
            n_matching_items.innerHTML = "";
        }
    }
    else {
        refreshBarChart();
        refreshAvailableItems();
        refreshMatchingItemsMessage();
    };
}

$('.ui.dropdown').dropdown();

function listIsNotEmpty(list_){
    if (list_.length > 0){
        result = true;
    }
    else {
        result = false;
    }
    return result; 
}

// Helpers :
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 LoadFirstDisplay(){
    application_title_button.className = "collapsible active";
    app_presentation_container.style.display = "block";
    app_helpers_containers.style.display = "none";
    initializeFrontendParameters();
}

LoadFirstDisplay();