(function () {
  var originalStringsSelect;

  $(document).ready(function () {
    setInverterInputsVisibility();

    $("#inverter_brand_id").change(submitInverterBrandForm);

    $("#inverter_quantity").change(setInverterInputsVisibility);

    $("#add_new_power_station").click(function () {
      showAddNewPowerStationForm();
    });
    $('#add_standalone_inverter').click(function () {
      showAddStandaloneInverterForm();
    });
    $('#add_supervisor_monitor').click(function () {
      showAddSupervisorMonitorForm();
    });

    for (var i = 1; i <= 4; i++) {
      var currentTarget = $("#inverter_" + i + "-model");
      currentTarget[0] && setInverterStringsOptions(currentTarget[0]);
      currentTarget.change(setInverterStringsOptionsFromEvent);
    }

    setInverterStringsOptions($("#inverter-model")[0]);
    $("#inverter-model").change(function (event) {
      setStandaloneInverterStringLimits();
      setInverterStringsOptions($("#inverter-model")[0]);
    });

    setupEditButtonHandlers('power_station', editPowerStation);
    setupEditButtonHandlers('standalone_inverter', editStandaloneInverter);
    setupEditButtonHandlers('supervisor_monitor', editSupervisorMonitor);
  });

  function submitInverterBrandForm() {
    $('form[name="inverter_brand_form"]').submit();
  }

  function setInverterInputsVisibility() {
    inverterQuantity = $('#inverter_quantity').val();

    for (var i = 1; i <= 4; i++) {
      if (i <= inverterQuantity) {
        $("#inverter_" + i + "_row").show();
      } else {
        $("#inverter_" + i + "_row").hide();
      }
    }
  }

  function setInverterStringsOptionsFromEvent(event) {
    setInverterStringsOptions(event.currentTarget);
  }

  function setStandaloneInverterStringLimits() {
    var inverterStringsPerInverterForm = $('#inverter-strings_per_inverter_row');
    var inverterStringsPerInverter = $('#inverter-strings_per_inverter');
    var inverterStringsPerInverterValue = inverterStringsPerInverter.val();
    var inverterModel = $('#inverter-model');
    var selectedStrings = inverterModel.val();
    var stringOptions = standaloneInverterStringLimits[selectedStrings];
    originalStringsSelect = originalStringsSelect || inverterStringsPerInverter.clone();
    inverterStringsPerInverter.empty();
    if (stringOptions && stringOptions.length) {
      originalStringsSelect
        .find('option')
        .each(function(i, opt) {
          if (stringOptions.indexOf(parseInt(opt.value)) > -1) {
            inverterStringsPerInverter.append($(opt).clone())
          }
        });
      inverterStringsPerInverter.val(inverterStringsPerInverterValue);
      inverterStringsPerInverterForm.css('display', 'inherit');
    } else {
      inverterStringsPerInverter.append($('<option selected value="0"></option>'));
      inverterStringsPerInverterForm.css('display', 'none');
    }
  }

  function setInverterStringsOptions(currentTarget) {
    var defaultStringValue = standaloneInverterStringDefaults[currentTarget.value];
    if (defaultStringValue) {
      var currentStringValue = defaultStringValue;
      var stringsId = currentTarget.id.replace("-model", "-strings_per_inverter");
      var stringsField = $("#" + stringsId);
      var options = stringsField[0].options;
      for (var i = 0; i < options.length; i++) {
        if (parseInt(options[i].value) <= parseInt(defaultStringValue)) {
          currentStringValue = options[i].value;
        } else {
          break;
        }
      }
      stringsField.val(currentStringValue);
    }
  }

  function setupEditButtonHandlers(name, editFunction) {
    var tableRowSelector = "." + name + "_table tr";
    var formId = "#" + name + "_form";
    var deleteLinkPrefix = '/delete_' + name + '/';

    $(tableRowSelector).each(function () {
      var table_row = $(this);
      var editButton = table_row.find("i.icon-pencil");
      if (editButton.length > 0) {
        var uuid = editButton.attr('id').split("edit_")[1];
        editButton.click(function () {
          $(tableRowSelector).each(function () {
            $(this).removeClass('selected');
          });
          table_row.addClass('selected');

          var deleteButton = $(formId + ' .delete_button');
          deleteButton.removeClass('hidden');
          deleteButton.attr('href', deleteLinkPrefix + uuid);

          editFunction(uuid);
        })
      }
    });
  }

  function editPowerStation(uuid) {
    var data = getObjectByUuid(uuid, powerStationData, 'power_station_id');

    if (data) {
      $('#power_station_id').val(uuid);
      $('#power_station_description').val(data['power_station_description']);
      $('#power_station_quantity').val(data['power_station_quantity']);
      $('#aux_plug').prop('checked', data['aux_plug']);
      $('#ac_run_length').val(data['ac_run_length']);

      $('#inverter_quantity').val(data['inverter_quantity']);
      setInverterInputsVisibility();

      var inverters = data['inverters'];
      for (var idx = 0; idx < inverters.length; idx++) {
        var inverter = inverters[idx];
        var prefix = '#inverter_' + (idx + 1);
        fillInverterData(inverter, prefix);
        $(prefix + '-model').val(inverter['model']);
        $(prefix + '-strings_per_inverter').val(inverter['strings_per_inverter']);
        $(prefix + '-sunshade').prop('checked', inverter['sunshade']);
        $(prefix + '-dc_switch').prop('checked', inverter['dc_switch']);
      }

      $('.ebom_form .submit input').val('Save');
    }

    showAddNewPowerStationForm();
  }

  function editStandaloneInverter(uuid) {
    data = getObjectByUuid(uuid, standaloneInverterData, 'standalone_inverter_id');

    if (data) {
      $('#standalone_inverter_id').val(uuid);
      $('#standalone_ac_run_length').val(data['ac_run_length']);
      $('#attachment-point').val(data['attachment_point'][0]);

      fillInverterData(data, '#inverter');

      $('#standalone_inverter_form .submit input').val('Save');
      $('#inverter-quantity_row').addClass('hidden');
    }
    showAddStandaloneInverterForm();
  }

  function editSupervisorMonitor(uuid) {
    data = getObjectByUuid(uuid, supervisorMonitorData, 'monitor_id');

    if (data) {
      $('#supervisor_monitor_form #monitor_id').val(uuid);
      var power_source = data['power_source'];
      if (power_source[0] !== 'Switch Gear/External') {
        $('#power_source').append($('<option>', {
          value: power_source[1],
          text: power_source[0]
        }));
        $('#power_source').val(data['power_source'][1]);
      }


      $('#supervisor_monitor_form .submit input').val('Save');
    }

    showAddSupervisorMonitorForm();
  }

  function fillInverterData(inverter, prefix) {
    $(prefix + '-model').val(inverter['model']);
    $(prefix + '-strings_per_inverter').val(inverter['strings_per_inverter']);
    $(prefix + '-sunshade').prop('checked', inverter['sunshade']);
    $(prefix + '-dc_switch').prop('checked', inverter['dc_switch']);
    $(prefix + '-splice_box').prop('checked', inverter['splice_box']);
  }

  function showAddNewPowerStationForm() {
    $("#add_new_power_station").addClass('disabled');
    $('#add_standalone_inverter').removeClass('disabled');
    $('#add_supervisor_monitor').removeClass('disabled');
    $('#power_station_form').removeClass('hidden');
    $('#supervisor_monitor_form').addClass('hidden');
    $('#standalone_inverter_form').addClass('hidden');
  }

  function showAddStandaloneInverterForm() {
    setStandaloneInverterStringLimits();
    $('#add_standalone_inverter').addClass('disabled');
    $('#add_new_power_station').removeClass('disabled');
    $('#add_supervisor_monitor').removeClass('disabled');
    $('#power_station_form').addClass('hidden');
    $('#supervisor_monitor_form').addClass('hidden');
    $('#standalone_inverter_form').removeClass('hidden');
  }

  function showAddSupervisorMonitorForm() {
    $('#add_supervisor_monitor').addClass('disabled');
    $('#add_standalone_inverter').removeClass('disabled');
    $('#add_new_power_station').removeClass('disabled');
    $('#power_station_form').addClass('hidden');
    $('#standalone_inverter_form').addClass('hidden');
    $('#supervisor_monitor_form').removeClass('hidden');
  }

  function getObjectByUuid(uuid, data, uuid_key) {
    for (var key in data) {
      if (data.hasOwnProperty(key)) {
        var val = data[key];
        if (val[uuid_key] == uuid) {
          return val;
        }
      }
    }
  }
})();
