// Add active class to the current control button (highlight it)
let recommendation_buttons_container = document.getElementById("recommendation_buttons_container");
let buttons = recommendation_buttons_container.getElementsByClassName("button");

function getActiveButton(){
  //buttons_status = {}
  for (let i = 0; i < buttons.length; i++) {
      current_button = buttons[i]
      if (current_button.className.includes("active")) {
            return current_button.id;
        }
  }
}; 

// divs : 
let rules_scope_container = document.getElementById("rules_scope_container");
let sort_ascending_container = document.getElementById("sort_ascending_container");
let rule_sope_button = document.getElementById("rule_sope_helper_button");
let rule_sope_helper_container = document.getElementById("rule_sope_helper_container");

// Buttons : 
let find_consequents_button = document.getElementById("find_consequents_button");
let find_antecedents_button = document.getElementById("find_antecedents_button");
let download_results_button = document.getElementById("download_results_button");

// Sliders :
let support_slider = document.getElementById("support_slider");
let support_value = document.getElementById("support_value");
support_value.innerHTML = support_slider.value;
support_slider.oninput = function() {
  support_value.innerHTML = `${this.value} %`;
}

let confidence_slider = document.getElementById("confidence_slider");
let confidence_value = document.getElementById("confidence_value");
confidence_value.innerHTML = confidence_slider.value;
confidence_slider.oninput = function() {
  confidence_value.innerHTML = this.value;
}
let lift_slider = document.getElementById("lift_slider");
let lift_value = document.getElementById("lift_value");
lift_value.innerHTML = lift_slider.value;
lift_slider.oninput = function() {
  lift_value.innerHTML = this.value;
}
let conviction_slider = document.getElementById("conviction_slider");
let conviction_value = document.getElementById("conviction_value");
conviction_value.innerHTML = conviction_slider.value;
conviction_slider.oninput = function() {
  conviction_value.innerHTML = this.value;
}


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

// Table :
let association_rules_table = document.getElementById("association_rules_table")

// Others :
let n_matching_rules = document.getElementById("n_matching_rules");

// Switch :
let sort_ascending = document.getElementById("sort_ascending");

// Events :
/// Buttons events : 
find_consequents_button.onclick =  function(){
    find_consequents_button.className = "button active"
    find_antecedents_button.className = "button"
    FilterResults();
};

find_antecedents_button.onclick =  function(){
    find_antecedents_button.className = "button active"
    find_consequents_button.className = "button"
    FilterResults();
};

download_results_button.onclick = function(){
    exportTableToCSV('rules_data.csv')
};
    
/// Sliders events :
confidence_slider.onchange = function(){
    FilterResults();
};
lift_slider.onchange = function(){
    FilterResults();
};
conviction_slider.onchange = function(){
    FilterResults();
};
support_slider.onchange = function(){
    FilterResults();
};

sort_ascending_container.onchange = function(){
    FilterResults();
};

/// Multiselect events :
items_selector.onchange = function(){
    FilterResults();
};

rules_scope_selector.onchange = function(){
    FilterResults();
};

metrics_priority_selector.onchange = function(){
    FilterResults();
    
};

// Table filtering
function FilterResults(){
    confidence = confidence_slider.value;
    lift = lift_slider.value;
    conviction = conviction_slider.value;
    support = support_slider.value;
    selected_items = getSelectValues(items_selector);
    selected_rule_scopes = getSelectValues(rules_scope_selector);
    metrics_priority = getSelectValues(metrics_priority_selector);
    sort_results_ascending = sort_ascending.checked;
    active_button = getActiveButton();
    
    console.log(`confidence : ${confidence}`);
    console.log(`lift : ${lift}`);
    console.log(`conviction : ${conviction}`);
    console.log(`support : ${support}`);
    console.log(`selected items : ${selected_items}`);
    console.log(`selected rule scopes : ${selected_rule_scopes}`);
    console.log(`metrics priority : ${metrics_priority}`);
    console.log(`active_button : ${active_button}`);
    console.log(`sort_ascending ? :${sort_results_ascending}`);
    
    filtering_parameters = {"selected_rule_scopes":selected_rule_scopes,
                            "confidence": confidence, "lift": lift, "conviction": conviction,
                            "metrics_priority": metrics_priority, "sort_results_ascending": sort_results_ascending,
                            "support": support, "selected_items": selected_items,
                            "active_button": active_button};
    $.ajax({
        type: "POST",
        method: "POST",
        url: getWebAppBackendUrl('filter_table_data')+'/',
        data: JSON.stringify(filtering_parameters),
        dataType:"json",
        success: function(backend_response){
            association_rules_table_data = backend_response["association_rules_table_data"];
            matching_rules_text = backend_response["matching_rules_text"];
            document.getElementById("dynamic_html_table").innerHTML = association_rules_table_data;
            n_matching_rules.innerHTML = matching_rules_text;
            
    }});
    
}


function loadFrontendStarter(){
    
    $.getJSON(getWebAppBackendUrl('load_rule_scopes_and_itemsets'+'/'),
        function(backend_response){
        compute_refined_rules = backend_response["compute_refined_rules"]
        association_rule_scopes = backend_response["association_rule_scopes"]
        if (compute_refined_rules) {
            enrich_html_select(association_rule_scopes, "rules_scope_selector", "option");
        }
        
        else {
            rules_scope_container.style.display = "none";
            rule_sope_button.style.display = "none";
            rule_sope_helper_container.style.display = "none";
        }
        
        rules_items = backend_response["rules_items"]
        enrich_html_select(rules_items, "items_selector", "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 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}`;
        //option.classList.add("TEST_BACKGROUND")
        html_element.add(option);
    });
}

function downloadCSV(csv, filename) {
    var csvFile;
    var downloadLink;
    // CSV file
    csvFile = new Blob([csv], {type: "text/csv"});
    // Download link
    downloadLink = document.createElement("a");
    // File name
    downloadLink.download = filename;
    // Create a link to the file
    downloadLink.href = window.URL.createObjectURL(csvFile);
    // Hide download link
    downloadLink.style.display = "none";
    // Add the link to DOM
    document.body.appendChild(downloadLink);
    // Click download link
    downloadLink.click();
}

function exportTableToCSV(filename) {
    var csv = [];
    var rows = document.querySelectorAll("table tr");
    for (var i = 0; i < rows.length; i++) {
        var row = [], cols = rows[i].querySelectorAll("td, th");
        for (var j = 0; j < cols.length; j++)
            row.push(cols[j].innerText);
        csv.push(row.join(";"));
    }
    // Download CSV file
    downloadCSV(csv.join("\n"), filename);
}

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

// 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";
    loadFrontendStarter()
}

LoadFirstDisplay();
