// Global array to store input names
var globalInputList = ['display_size', 'file', 'association_measures', 'complexity_measures', 'labeled_trees', 'node_type_upos', 'fixed_order', 'input_url', 'node_type_lemma', 'root_restriction', 'node_type_form', 'frequency_threshold', 'node_type_none', 'query', 'compare_url', 'compare_file', 'ignored_labels', 'complete_trees'];
var visualInputList = ['advanced-tree-expand', 'compare-expand']

// Function to store values to local storage
function storeValuesToLocalstorage() {
    globalInputList.forEach(function(inputName) {
        var inputElement = $('[name="' + inputName + '"]');

        if (inputElement.length > 0) {
            var inputType = inputElement.attr('type');
            if (inputType === 'text' | inputType === 'hidden') {
                localStorage.setItem(inputName, inputElement.val());
            } else if (inputType === 'checkbox') {
                localStorage.setItem(inputName, inputElement.prop('checked'));
            }
        }
    });
    visualInputList.forEach(function(inputName) {
        var shown = $('#' + inputName).find('i').text().trim() === 'add';
        localStorage.setItem(inputName, shown);
    });
}

// Function to read values from local storage
function readValuesFromLocalstorage() {
    globalInputList.forEach(function(inputName) {
        var inputElement = $('[name="' + inputName + '"]');

        if (inputElement.length > 0) {
            var inputType = inputElement.attr('type');
            if (inputType === 'text') {
                var text_val = localStorage.getItem(inputName);
                if (text_val !== '' & text_val !== null) {
                    // set label to active
                    $("label[for='" + inputElement.attr('id') + "']").addClass('active');
                }
                if (inputName === 'frequency_threshold' && text_val === null) {
                    text_val = '1'
                }
                if (inputName === 'display_size' && text_val === null) {
                    text_val = '2-10'
                }
                inputElement.val(text_val);

            } else if (inputType === 'checkbox') {
                var check_value = localStorage.getItem(inputName);
                if (check_value !== null) {
                    inputElement.prop('checked', check_value === 'true');
                }
                if (inputName === 'node_type_none' && check_value === null) {
                    $('input.association_measures').prop('disabled', true);
                    $('input.association_measures').prop('checked', false);
                } else if(inputName === 'node_type_none' && check_value == 'true') {
                    $('input.association_measures').prop('disabled', true);
                    $('input.association_measures').prop('checked', false);
                }
            }
        }

    });
    var tree_size_min = localStorage.getItem('tree_size_min') !== null ? localStorage.getItem('tree_size_min') : 2;
    var tree_size_max = localStorage.getItem('tree_size_max') !== null ? localStorage.getItem('tree_size_max') : 3;
    return [tree_size_min, tree_size_max]
}

function readVariableFromLocalstorage(variableName) {
    if (localStorage.getItem(variableName) === null) {
        return true;
    }
    return localStorage.getItem(variableName) === 'true';
};


document.addEventListener("DOMContentLoaded", function(event) {
  tree_size = readValuesFromLocalstorage()

  var valuesForSlider = [1,2,3,4,5];

  var format = {
      to: function(value) {
        return valuesForSlider[Math.round(value)];
      },
      from: function (value) {
        return valuesForSlider.indexOf(Number(value));
      }
    };
  var urlParams = new URLSearchParams(window.location.search);
  var lang='en'
  if (urlParams.has('lang')) {
    lang=urlParams.get('lang');
  }

  var perfEntries = performance.getEntriesByType("navigation");
  for (var i = 0; i < perfEntries.length; i++) {
    if (perfEntries[i].type === 'back_forward') {
      window.location.href = '/stark/?lang='+lang;
      return;
    }
  }


  if (urlParams.has('reload')) {
      localStorage.clear();
      window.location.href = '/stark/?lang='+lang;

  }
});

function adjustLabelPosition() {
  $('.dynamic-height').each(function() {
    var $label = $(this).find('label');
    var $input = $(this).find('input');

    // Get the original top and left positions
    var originalTop = parseFloat($label.css('top'));
    var labelHeight = parseFloat($label.css('height'));
    var labelLineHeight = parseFloat($label.css('line-height'));
    var heightDelta = (Math.floor(labelHeight / labelLineHeight) - 1) * labelLineHeight;

    $label.css({
      top: -heightDelta
    });
  });
}

(function($){
  $(function(){

    $('.sidenav').sidenav();

  });
  $(document).ready(function(){
    $('.modal').modal();

    $('.input-field input[type="checkbox"]').on('change', function() {
      var isChecked = $('.input-field input[type="checkbox"]:checked').length > 0;
      $('#node-type-error').hide();
    });
    $('#submit-form input').on('change', function() {
      $('#unknown-error').hide();
    });

    var advancedTreeExpanded = readVariableFromLocalstorage('advanced-tree-expand');
    if (!advancedTreeExpanded) {
        advancedTreeExpanded = true;
        $('#advanced-tree').show('fast', function() {
          adjustLabelPosition();
        });
        $('#advanced-tree-expand i').text('remove');
    } else {
        advancedTreeExpanded = false;
        $('#advanced-tree').hide('fast');
        $('#advanced-tree-expand i').text('add');
    }
    $('#advanced-tree-expand').bind('click', function(e) {
      if (!advancedTreeExpanded){
        advancedTreeExpanded = true;
        $('#advanced-tree').show('fast', function() {
          adjustLabelPosition();
        });
        $('#advanced-tree-expand i').text('remove');
      } else {
        advancedTreeExpanded = false;
        $('#advanced-tree').hide('fast');
        $('#advanced-tree-expand i').text('add');
      }
    });

    var compareExpanded = readVariableFromLocalstorage('compare-expand');
    if (!compareExpanded) {
        compareExpanded = true;
        $('#compare-settings').show('fast', function() {
          adjustLabelPosition();
        });
        $('#compare-expand i').text('remove');
    } else {
        compareExpanded = false;
        $('#compare-settings').hide('fast');
        $('#compare-expand i').text('add');
    }

    $('#compare-expand').bind('click', function(e) {
      if (!compareExpanded){
        compareExpanded = true;
        $('#compare-settings').show('fast', function() {
          adjustLabelPosition();
        });
        $('#compare-expand i').text('remove');
      } else {
        compareExpanded = false;
        $('#compare-settings').hide('fast');
        $('#compare-expand i').text('add');
      }
    });

  });

  $("#submit-form").submit( function(eventObj) {
    storeValuesToLocalstorage();
    return true;
  });
  $("#switch-language").click(function(e) {
    storeValuesToLocalstorage();
    return true;
  });
  $('input.node_type').on('change', function(e) {
    if (this.name == 'node_type_none') {
      $('input.node_type').not(this).prop('checked', false);
      $('input.association_measures').prop('disabled', true);
      $('input.association_measures').prop('checked', false);
    } else {
      $('input.node_type_none').prop('checked', false);
      $('input.association_measures').prop('disabled', false);
    }
  });
  $('input.complete_trees').on('change', function(e) {
    if(this.checked === false) {
        // $('.modal2').modal('open');
        $('#modal2').modal('open');
    }
  });
  $('a.example-input-link').click(function(e) {
    $('#input_url').val(this.href)
    $('label[for="input_url"]').addClass('active')
    e.preventDefault();
  });
  $('a.example-compare-link').click(function(e) {
    $('#compare_url').val(this.href)
    $('label[for="compare_url"]').addClass('active')
    e.preventDefault();
  });

  // Initial adjustment
  adjustLabelPosition();

  // Adjust on window resize
  $(window).resize(adjustLabelPosition);


})(jQuery);

