(function (context, $) {

  "use strict";
  context.JK = context.JK || {};
  context.JK.EditRecordingDialog = function (app) {
    var logger = context.JK.logger;
    var rest = context.JK.Rest();
    var claimedRecordingId = null;
    var $dialog = null;
    var $form = null;
    var $name = null;
    var $description = null;
    var $genre = null;
    var $isPublic = null;
    var $saveBtn = null;
    var $deleteBtn = null;
    var $videoField = null;
    var updating = false;
    var deleting = false;

    function resetForm() {

      // remove all display errors
      $dialog.find('.error-text').remove()
      $dialog.find('.error').removeClass("error")
    }

    function beforeShow(args) {

      claimedRecordingId = args.d1;

      if(!claimedRecordingId) throw "claimedRecordingId must be specified";

      resetForm();

      rest.getClaimedRecording(claimedRecordingId)
        .done(function(data) {
          var name = data.name;
          var description = data.description;
          var is_public = data.is_public;
          var genre_id = data.genre_id;

          context.JK.GenreSelectorHelper.setSelectedGenres($genre.parent(), [genre_id]);
          $name.val(name);
          $description.val(description);
          if(is_public) {
            $isPublic.attr('checked', 'checked').iCheck('check')
          }
          else {
            $isPublic.removeAttr('checked').iCheck('uncheck')
          }
        })
        .fail(app.ajaxError)
    }

    function afterHide() {

    }

    function attemptUpdate() {
      if(updating) return;

      updating = true;
      var name = $name.val();
      var description = $description.val();
      var genre = $genre.val();
      var is_public = $isPublic.is(':checked');

      rest.updateClaimedRecording({id: claimedRecordingId, name: name, description: description, is_public: is_public, genre: genre })
        .done(function(updated) {
          resetForm();
          $dialog.triggerHandler('recording_updated', {id: claimedRecordingId, name: name, description: description, is_public: is_public, genre: genre})
          app.layout.closeDialog('edit-recording');
        })
        .fail(function(jqXHR) {

          if(jqXHR.status = 422) {
            // highlight fields in error

            resetForm();

            var errors = JSON.parse(jqXHR.responseText);

            var $name_errors = context.JK.format_errors('name', errors);
            if ($name_errors) $name.closest('div.field').addClass('error').end().after($name_errors);

            var $description_errors = context.JK.format_errors('description', errors);
            if ($description_errors) $description.closest('div.field').addClass('error').end().after($description_errors);

            var $genre_errors = context.JK.format_errors('genre', errors);
            if ($genre_errors) $genre.closest('div.field').addClass('error').end().after($genre_errors);

            var $is_public_errors = context.JK.format_errors('is_public', errors);
            if ($is_public_errors) $isPublic.closest('div.field').addClass('error').end().after($is_public_errors);

          }
          else {
            app.ajaxError(arguments);
          }
        })
        .always(function() {
          updating = false;
        })
    }

    function attemptDelete() {
      if(deleting) return;

      deleting = true;
      context.JK.Banner.showYesNo({
        title: "Confirm Deletion",
        html: "Are you sure you want to delete this recording?",
        yes: function() {
          rest.deleteClaimedRecording(claimedRecordingId)
            .done(function() {
              $dialog.triggerHandler('recording_deleted', {id: claimedRecordingId});
              app.layout.closeDialog('edit-recording');
            })
            .fail(app.ajaxError)
            .always(function() {
              deleting = false;
            })
        },
        no : function() {
          context.JK.Banner.hide();
          deleting = false;
        }
      })
    }

    function events() {
      $saveBtn.click(attemptUpdate);
      $deleteBtn.click(attemptDelete);
      $form.submit(false);
    }


    function initialize() {
      var dialogBindings = {
        'beforeShow': beforeShow,
        'afterHide': afterHide
      };

      app.bindDialog('edit-recording', dialogBindings);

      $dialog = $('#edit-recording-dialog');
      $form = $dialog.find('form');
      $saveBtn = $dialog.find('.save-btn');
      $deleteBtn = $dialog.find('.delete-btn');
      $name = $dialog.find('input[name="name"]');
      $description = $dialog.find('textarea[name="description"]');
      $genre = $dialog.find('select[name=genre]');
      $isPublic = $dialog.find('input[name=is_public]');

      events();

      context.JK.GenreSelectorHelper.render($genre.parent());
      context.JK.checkbox($isPublic);
    };

    this.initialize = initialize;
  }
})(window, jQuery);