(function(){
  EASY.pageTab = EASY.pageTab || {}

  EASY.pageTab.addFilter = function(type, filter){
    // Just in case
    if (!type) { return }

    var name = ""
    var possibleValues = ""

    // Loading saved filter
    if (filter) {
      name = filter.name
      possibleValues = filter.possible_values
    }

    var filterId = $.now()
    var filterType = availableFiltersTypes[type]

    var filterDef =
      "<tr class='tab-controls__filter-def' data-filter-id='"+filterId+"'>" +
      "  <td><label><input type='checkbox' checked>"+filterType.name+"</label></td>" +
      "  <td>" +
      "    <input type='text' name='filters_settings["+filterId+"][name]' placeholder='"+I18n.textPleaseFillName+" ...' value='"+name+"'>" +
      "    <input type='hidden' name='filters_settings["+filterId+"][type]' value='"+type+"'>" +
      "  </td>" +
      "</tr>"

    if (filterType.manual_possible_values) {
      filterDef +=
        "<tr style='border: none'>" +
        "  <td style='vertical-align: top'><label>"+I18n.fieldPossibleValues+"</label></td>" +
        "  <td><textarea name='filters_settings["+filterId+"][possible_values]' rows='10' style='max-width: 350px'>"+possibleValues+"</textarea></td>" +
        "</tr>"
    }

    $(".tab-controls__form tr:last").before(filterDef)

    $.each(modulesFiltersOptions, function(uuid, queriesSettings){
      $.each(queriesSettings, function(key, filtersOptions){

        var attributes = filtersOptions[type]
        if (attributes) {
          var options = "<option></option>"

          $.each(attributes, function(i, attribute){
            var name = attribute[0]
            var field = attribute[1]

            options += "<option value='"+field+"'>"+name+"</option>"
          })

          var html = "<tr class='tab-controls__filter-use' data-filter-id='"+filterId+"'>"+
                     "  <td><label>"+(name || '---')+"</label></td>" +
                     "  <td><select name='filters_settings["+filterId+"][modules]["+uuid+"]["+key+"]'>"+options+"</select></td>" +
                     "</tr>"

          $("#module_inside_"+uuid+" table.tab-controls__query--"+key).append(html)
        }

      })
    })

    $(".tab-controls__select-type").val("")

    return filterId
  }

  EASY.pageTab.save = function(){
    var $form = $(".tab-controls__form")

    $(".easy-page-module [name^='filters_settings']:enabled").each(function(){
      $form.append(
        "<input type='hidden' name='"+this.name+"' value='"+this.value+"'>"
      )
    })

    $form.submit()
  }

  // TODO: Make it nicer
  EASY.pageTab.loadModuleFilters = function(filterId, modulesSettings){
    $.each(modulesSettings, function(uuid, moduleSettings){
      $.each(moduleSettings, function(key, field){
        $("[name='filters_settings["+filterId+"][modules]["+uuid+"]["+key+"]']").val(field)
      })
    })
  }

  EASY.pageTab.initSettings = function(filters){
    $(".module-content").each(function(){
      var uuid = this.id.replace("module_inside_", "")
      var queriesSettings = modulesFiltersOptions[uuid]
      var self = this

      if (queriesSettings && !$.isEmptyObject(queriesSettings)) {
        self.innerHTML = ""

        $.each(queriesSettings, function(key, filtersOptions){
          if (key != "nil") { self.innerHTML += "<h4>"+I18n.labelFilterPlural+": "+key+"</h4>" }
          else              { self.innerHTML += "<h4>"+I18n.labelFilterPlural+"</h4>" }

          self.innerHTML += "<table style='width: auto; margin: 10px 0' class='tab-controls__query--"+key+"'></table>"
        })
      }
      else {
        self.innerHTML = "<p>--- "+I18n.labelNoFiltersDetected+" ---</p>"
      }
    })

    // Automatically change label (on modules) based on definition
    $("#content").on("keyup", ".tab-controls__filter-def input[type='text']", function(){
      // tr > td > input
      var filterId = this.parentElement.parentElement.dataset.filterId
      $(".tab-controls__filter-use[data-filter-id='"+filterId+"'] label").text(this.value)
    })

    $("#content").on("change", ".tab-controls__filter-def input[type='checkbox']", function(){
      // tr > td > label > input
      var filterId = this.parentElement.parentElement.parentElement.dataset.filterId
      $(".tab-controls__filter-use[data-filter-id='"+filterId+"']").toggle(this.checked)
      $("[data-filter-id='"+filterId+"'] [name^='filters_settings']").prop("disabled", !this.checked)
    })

    for (var i = 0; i < filters.length; i++) {
      var filter = filters[i]
      var filterId = EASY.pageTab.addFilter(filter.type, filter)
      EASY.pageTab.loadModuleFilters(filterId, filter.modules)
    }
  }

  EASY.pageTab.applyFilters = function(link){
    var data = $(".tab-filter__field select, .tab-filter__field input").serializeArray()

    $.ajax({
      url: link.dataset.applyUrl,
      data: data,
      success: function(data){
        $("#easy_jquery_tab_panel-"+link.dataset.tabId).html(data)
        ERUI.document.trigger("tab-change")
      }
    });
  }

})()
