(function(context,$) {

  context.JK = context.JK || {};
  context.JK.SessionSettingsDialog = function(app) {
    var logger = context.JK.logger;
    var gearUtils = context.JK.GearUtilsInstance;
    var $dialog;
    var $screen = $('#session-settings');
    //var $selectedFilenames = $screen.find('#selected-filenames');
    var $uploadSpinner = $screen.find('.spinner-small');
    //var $selectedFilenames = $('#settings-selected-filenames');
    var $inputFiles = $screen.find('#session-select-files');
    var $btnSelectFiles = $screen.find('.btn-select-files');
    var $inputBox = $screen.find('.inputbox')
    var rest = new JK.Rest();
    var sessionId;

    function beforeShow(data) {

      var canPlayWithOthers = gearUtils.canPlayWithOthers();

      context.JK.GenreSelectorHelper.render('#session-settings-genre');
      $dialog = $('[layout-id="session-settings"]');

      var currentSession = context.SessionStore.currentSession;
      sessionId = currentSession.id;

      // id
      $('#session-settings-id').val(currentSession.id);

      // genre
      context.JK.GenreSelectorHelper.setSelectedGenres('#session-settings-genre', currentSession.genres);

      // name
      $('#session-settings-name').val(currentSession.name);

      // description
      $('#session-settings-description').val(currentSession.description);

      // language
      $('#session-settings-description').val(currentSession.language);

      // musician access
      if (!currentSession.musician_access && !currentSession.approval_required) {
        $('#session-settings-musician-access').val('only-rsvp');
      }
      
      else if (currentSession.musician_access && currentSession.approval_required) {
        $('#session-settings-musician-access').val('musicians-approval');
      }

      else if (currentSession.musician_access && !currentSession.approval_required) {
        $('#session-settings-musician-access').val('musicians');
      }

      // fan access
      if (!currentSession.fan_access && !currentSession.fan_chat) {
        $('#session-settings-fan-access').val('no-listen-chat');
      }
      
      else if (currentSession.fan_access && !currentSession.fan_chat) {
        $('#session-settings-fan-access').val('listen-chat-each');
      }

      else if (currentSession.fan_access && currentSession.fan_chat) {
        $('#session-settings-fan-access').val('listen-chat-band');
      }

      // friends can join

      var friendsCanJoinValue = currentSession.friends_can_join ? "true" : "false"
      $('#session-settings-friends-can-join').val(friendsCanJoinValue)

      var $controllerSelect = $('#session-settings-master-mix-controller')

      $controllerSelect.empty()
      var sessionUsers = context.SessionStore.helper.users()

      $controllerSelect.append('<option value="">Any one can control the Master Mix</option>')
      $.each(sessionUsers, function(userId, user) {
        var selected = currentSession.session_controller_id == userId ? 'selected="selected"' : ''
        $controllerSelect.append('<option value="' + userId + '"' + selected + '>' + user.name +'</option>')
      })

      var canEditController = currentSession.session_controller_id == context.JK.currentUserId || context.JK.currentUserId == currentSession.user_id
      $controllerSelect.easyDropDown(canEditController ? 'enable' : 'disable')

      /**
      // notation files in the account screen. ugh.
      $selectedFilenames.empty();
      for (var i=0; i < currentSession.music_notations.length; i++) {
        var notation = currentSession.music_notations[i];
        $selectedFilenames.append('<a href="' + notation.file_url + '" rel="external">' + notation.file_name + '</a>&nbsp;');
      }*/

      $inputBox.empty();
      for (var i=0; i < currentSession.music_notations.length; i++) {
        var notation = currentSession.music_notations[i];
        addNotation(notation)
      }


      context.JK.dropdown($('#session-settings-language'));
      context.JK.dropdown($('#session-settings-musician-access'));
      context.JK.dropdown($('#session-settings-fan-access'));
      context.JK.dropdown($('#session-settings-friends-can-join'));
      context.JK.dropdown($('#session-settings-master-mix-controller'));

      var easyDropDownState = canPlayWithOthers.canPlay ? 'enable' : 'disable'
      $('#session-settings-musician-access').easyDropDown(easyDropDownState)
      $('#session-settings-fan-access').easyDropDown(easyDropDownState)


    }

    function addNotation(notation) {

      var $notation = $('<div class="notation-entry"><div>' + notation.file_name + '</div><a href="#" data-id="' + notation.id + '">X</a></div>')
      $notation.find('a').on('click', function(e) {

        if($(this).attr('data-deleting')) {
          // ignore duplicate delete attempts
          return false;
        }

        $(this).attr('data-deleting', true)
        var $notationEntry = $(this).closest('.notation-entry').find('div').text('deleting...')

        rest.deleteMusicNotation({id: notation.id})
          .done(function() {
            $notation.remove()
          })
          .fail(app.ajaxError)
        return false;
      })
      $inputBox.append($notation);
    }

    function saveSettings(evt) {

      var data = {};

      data.genre = context.JK.GenreSelectorHelper.getSelectedGenres('#session-settings-genre')[0];
      data.name = $('#session-settings-name').val();
      data.description = $('#session-settings-description').val();
      data.language = $('#session-settings-language').val();
      data.session_controller = $('#session-settings-master-mix-controller').val()

      // musician access
      var musicianAccess = $('#session-settings-musician-access').val();
      if (musicianAccess === 'only-rsvp') {
        data.musician_access = false;
        data.approval_required = false;
      }
      else if (musicianAccess === 'musicians-approval') {
        data.musician_access = true;
        data.approval_required = true;
      }
      else if (musicianAccess === 'musicians') {
        data.musician_access = true;
        data.approval_required = false;
      }

      // fan access
      var fanAccess = $('#session-settings-fan-access').val();
      if (fanAccess == 'no-listen-chat') {
        data.fan_access = false;
        data.fan_chat = false;
      }
      else if (fanAccess == 'listen-chat') {
        data.fan_access = true;
        data.fan_chat = true;
      }

      var friendsCanJoin = $('#session-settings-friends-can-join').val();
      if (friendsCanJoin == 'true') {
        data.friends_can_join = true
      }
      else {
        data.friends_can_join = false
      }

      rest.updateSession($('#session-settings-id').val(), data).done(settingsSaved)
      .done(function(response) {
          context.SessionActions.updateSession.trigger(response);
        })
      .fail(function() {
          app.notify({title: "Can't Update", text: "Unable to update session settings."})
        })

      return false;
    }

    function uploadNotations(notations) {

      var formData = new FormData();
      var maxExceeded = false;

      $.each(notations, function(i, file) {
        var max =  10 * 1024 * 1024;
        if(file.size > max) {
          maxExceeded = true;
          return false;
        }
        formData.append('files[]', file);
      });

      if(maxExceeded) {
        app.notify(
          { title: "Maximum Music Notation Size Exceeded",
            text: "You can only upload files up to 10 megabytes in size."
          });
        var deferred = new $.Deferred();
        deferred.reject();
        return deferred;
      }

      formData.append('client_id', app.clientId);
      formData.append('session_id', sessionId);
      $btnSelectFiles.text('UPLOADING...').data('uploading', true)
      $uploadSpinner.show();
      return rest.uploadMusicNotations(formData)
        .done(function(response) {
          var error_files = [];
          $.each(response, function(i, music_notation) {
            if (music_notation.errors) {
              error_files.push(music_notation.name);
            }
          })
          if (error_files.length > 0) {
            app.notifyAlert("Failed to upload notations.", error_files.join(', '));
          }
        })
        .fail(function(jqXHR) {
          if(jqXHR.status == 413) {
            // the file is too big.   Let the user know.
            // This should happen when they select the file, but a misconfiguration on the server could cause this.
            app.notify(
              { title: "Maximum Music Notation Size Exceeded",
                text: "You can only upload files up to 10 megabytes in size."
              })
          }
          else {
            app.notifyServerError(jqXHR, "Unable to upload music notations");
          }
        })
        .always(function() {
          $btnSelectFiles.text('ADD FILES...').data('uploading', null)
          $uploadSpinner.hide();
        });
    }

    function changeSelectedFiles() {
      var fileNames = [];
      var files = $inputFiles.get(0).files;
      var error = false;
      for (var i = 0; i < files.length; ++i) {
        var name = files.item(i).name;
        var ext = name.split('.').pop().toLowerCase();
        if ($.inArray(ext, ["pdf", "png", "jpg", "jpeg", "gif", "xml", "mxl", "txt"]) == -1) {
          error = true;
          break;
        }
        fileNames.push(name);
      }

      if (error) {
        app.notifyAlert("Error", "We're sorry, but you can only upload images (.png .jpg .jpeg .gif), text (.txt), PDFs (.pdf), and XML files (.xml .mxl).");
        $inputFiles.replaceWith($inputFiles.clone(true));
      }
      else {
        // upload as soon as user picks their files.
        uploadNotations($inputFiles.get(0).files)
          .done(function(response) {
            context._.each(response, function(notation) {
              addNotation(notation)
            })
          })
      }
    }

    function toggleSelectFiles(event) {
      if($btnSelectFiles.data('uploading')) {
        logger.debug("ignoring click of SELECT FILES... while uploading")
        return false;
      }

      event.preventDefault();
      $inputFiles.trigger('click');
      return false;
    }

    function settingsSaved(response) {
      // No response returned from this call. 204.
      context.SessionActions.syncWithServer()
      app.layout.closeDialog('session-settings');
    }

    function events() {
      $('#session-settings-dialog-submit').on('click', saveSettings);
      $('#session-settings-dialog').on('submit', saveSettings)
      $inputFiles.on('change', changeSelectedFiles);
      $btnSelectFiles.on('click', toggleSelectFiles);
    }

    this.initialize = function() {
      events();
      var dialogBindings = {
        'beforeShow': beforeShow
      };

      app.bindDialog('session-settings', dialogBindings);
    };
  };
})(window,jQuery);