
(function(context,$) {

  "use strict";

  context.JK = context.JK || {};
  context.JK.AccountProfileExperience = function(app) {
    var $document = $(document);
    var logger = context.JK.logger;
    var EVENTS = context.JK.EVENTS;
    var api = context.JK.Rest();
    var $screen = $('#account-profile-experience');
    var profileUtils = context.JK.ProfileUtils;
    var $btnCancel = $screen.find('.account-edit-profile-cancel');
    var $btnBack = $screen.find('.account-edit-profile-back');
    var $btnSubmit = $screen.find('.account-edit-profile-submit');

    var $instrumentSelector = $screen.find('.instrument_selector');
    var $userGenres = $screen.find('#user-genres');

    function beforeShow(data) {
    }

    function afterShow(data) {

      if (window.ProfileStore.solo) {
        $btnBack.hide()
        $btnSubmit.text('SAVE & RETURN TO PROFILE');
      }
      else {
        $btnBack.show()
        $btnSubmit.text('SAVE & NEXT');
      }

      resetForm();
      renderExperience();
    }

    function resetForm() {
      $screen.find('form .error-text').remove();
      $screen.find('form .error').removeClass("error");
    }

    function populateAccountProfile(userDetail, instruments) {

      loadGenres(profileUtils.profileGenres(userDetail.genres));

      $instrumentSelector.empty();
      $.each(instruments, function(index, instrument) {
        var template = context.JK.fillTemplate($('#account-profile-instrument').html(), {
          checked : isUserInstrument(instrument, userDetail.instruments) ? "checked=\"checked\"" :"",
          description : instrument.description,
          id : instrument.id
        });
        $instrumentSelector.append(template);
      });

      // and fill in the proficiency for the instruments that the user can play
      if(userDetail.instruments) {
        $.each(userDetail.instruments, function(index, userInstrument) {
          $('tr[data-instrument-id="' + userInstrument.instrument_id + '"] select.proficiency_selector', $screen).val(userInstrument.proficiency_level);
        });
      }

      $screen.find('select[name=skill_level]').val(userDetail.skill_level);
      $screen.find('select[name=concert_count]').val(userDetail.concert_count);
      $screen.find('select[name=studio_session_count]').val(userDetail.studio_session_count);
      context.JK.checkbox($instrumentSelector.find('input[type="checkbox"]'), true)
    }

    function isUserInstrument(instrument, userInstruments) {
      var isUserInstrument = false;
      if(!userInstruments) return false;

      $.each(userInstruments, function(index, userInstrument) {
        if(instrument.id == userInstrument.instrument_id) {
          isUserInstrument = true;
          return false;
        }
      });
      return isUserInstrument;
    }

    function loadGenres(selectedGenres) {
      $userGenres.empty();

      rest.getGenres().done(function (genres) {
        $.each(genres, function (index, genre) {
          var genreTemplate = $('#template-user-setup-genres').html();
          var selected = '';
          if (selectedGenres) {
            var genreMatch = $.grep(selectedGenres, function (n, i) {
              return n.genre_id === genre.id;
            });
            if (genreMatch.length > 0) {
              selected = "checked";
            }
          }
          var genreHtml = context.JK.fillTemplate(genreTemplate, {
            id: genre.id,
            description: genre.description,
            checked: selected
          });
          $userGenres.append(genreHtml);
        });

        context.JK.checkbox($userGenres.find('input[type="checkbox"]'), true)
      });
    }

    function resetGenres() {
      $('input[type=checkbox]:checked', $userGenres).each(function (i) {
        $(this).removeAttr("checked");
      });
      var $tdGenres = $("#tdBandGenres");
    }

    function getSelectedGenres() {
      var genres = [];
      $('input[type=checkbox]:checked', $userGenres).each(function (i) {
        var genre = $(this).val();
        genres.push(genre);
      });
      return genres;
    }

    function events() {
      $btnCancel.click(function(evt) {
        evt.stopPropagation();
        window.ProfileActions.cancelProfileEdit()
        return false;
      });

      $btnBack.click(function(evt) {
        evt.stopPropagation();
        navigateTo('/client#/account/profile/');
        return false;
      });

      enableSubmits()
    }

    function enableSubmits() {
      $btnSubmit.on("click", function(evt) {
        evt.stopPropagation();
        handleUpdateProfile();
        return false;
      });

      $btnSubmit.removeClass("disabled")
    }

    function disableSubmits() {
      $btnSubmit.addClass("disabled")
      $btnSubmit.off("click")
    }

    function renderExperience() {
      $.when(api.getUserProfile(), api.getInstruments())
        .done(function(userDetailResponse, instrumentsResponse) {
          var userDetail = userDetailResponse[0];
          populateAccountProfile(userDetail, instrumentsResponse[0]);
        });
    }

    function navigateTo(targetLocation) {
      resetForm();
      context.location = targetLocation;
    }

    function handleUpdateProfile() {
      disableSubmits()
      resetForm();

      var instruments = getSelectedInstruments();
      var genres = getSelectedGenres();

      api.updateUser({
        instruments: instruments,
        genres: genres,
        skill_level: $screen.find('select[name=skill_level]').val(),
        concert_count: $screen.find('select[name=concert_count]').val(),
        studio_session_count: $screen.find('select[name=studio_session_count]').val()
      })
        .done(postUpdateProfileSuccess)
        .fail(postUpdateProfileFailure)
        .always(enableSubmits)
    }

    function postUpdateProfileSuccess(response) {
      $document.triggerHandler(EVENTS.USER_UPDATED, response);
      ProfileActions.editProfileNext('interests')
    }

    function postUpdateProfileFailure(xhr, textStatus, errorMessage) {

      var errors = JSON.parse(xhr.responseText)

      if(xhr.status == 422) {
        var instruments = context.JK.format_errors("musician_instruments", errors);

        if(instruments != null) {
          $instrumentSelector.closest('div.field').addClass('error').append(instruments);
        }
      }
      else {
        app.ajaxError(xhr, textStatus, errorMessage)
      }
    }

    function getSelectedInstruments() {
      var instruments = [];
      $('input[type=checkbox]:checked', $instrumentSelector).each(function(i) {

        var instrumentElement = $(this).closest('tr');
        // traverse up to common parent of this instrument, and pick out proficiency selector
        var proficiency = $('select.proficiency_selector', instrumentElement).val();

        instruments.push({
          instrument_id: instrumentElement.attr('data-instrument-id'),
          proficiency_level: proficiency,
          priority : i
        });
      });

      return instruments;
    }

    function initialize() {
      var screenBindings = {
        'beforeShow': beforeShow,
        'afterShow': afterShow
      };

      app.bindScreen('account/profile/experience', screenBindings);

      events();
    }

    this.initialize = initialize;
    this.beforeShow = beforeShow;
    this.afterShow = afterShow;
    return this;
  };

})(window,jQuery);
