// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Event handlers for the resource management page.
 */

// Note the one-character difference from layermanager.resources, a
// different namespace used for defining data written by the template.
layermanager.resource = {};


/** The maximum width and height of a regular thumbnail, in pixels. */
layermanager.resource.THUMBNAIL_SIZE = 200;
/** The maximum width and height of a small thumbnail, in pixels. */
layermanager.resource.SMALL_THUMBNAIL_SIZE = 100;
/**
  * If there are at least this many resources to display, show them in small
  * rather than regular thumbnails.
  */
layermanager.resource.THUMBNAIL_THRESHOLD = 75;

/**
 * Deletes the currently selected resource.
 * @this {Element} A .resource-delete span that is contained inside a
 *     .resource-block div with a jQuery data field named "id" containing the
 *     ID of the resource to delete. Such elements are generated by
 *     refreshList().
 */
layermanager.resource.destroy = layermanager.util.makeHandler({
  action: 'delete',
  type: 'resource',
  collect: function() {
    // Including the type to pass it to the success function. It's ignored by
    // the backend.
    return {resource_id: jQuery(this).closest('.resource-block').data('id'),
            type: jQuery('#resource_list_type').val()};
  },
  validate: function() {
    return confirm('Are you sure you want to delete this resource?');
  },
  succeed: function(_, fields) {
    delete layermanager.resources.files[fields.type][fields.resource_id];
    layermanager.resource.refreshList();
  }
});

/**
  * Refills the resource selection box with resource blocks of the currently
  * selected type. Also sets up events for the added resource blocks.
  */
layermanager.resource.refreshList = function() {
  var type = jQuery('#resource_list_type').val();
  var list = jQuery('#resource_list');
  var resourceList = layermanager.resources.files[type];
  var resourceCount = 0;
  jQuery.each(resourceList, function() { resourceCount++; });
  var size = (resourceCount >= layermanager.resource.THUMBNAIL_THRESHOLD) ?
             layermanager.resource.SMALL_THUMBNAIL_SIZE :
             layermanager.resource.THUMBNAIL_SIZE;

  list.html('');

  if (jQuery.isEmptyObject(resourceList)) {
    list.append('<div class="resource-empty">No resources of this type.</div>');
    return;
  }

  jQuery.each(resourceList, function(key, name) {
    var fullsizeUrl = layermanager.util.getResourceUrl(key);
    var thumbnailUrl;

    if (type == 'raw' || type == 'model' || type == 'model_in_kmz') {
      thumbnailUrl = '/static/img/resource_model.png';
    } else if (type == 'image') {
      thumbnailUrl = layermanager.util.getResourceUrl(key, size);
    } else if (type == 'icon') {
      thumbnailUrl = fullsizeUrl;
    } else {
      layermanager.ui.reportError('Invalid resource type selected.');
    }

    var block = jQuery('<div class="resource-block">').hover(function() {
      jQuery(this).toggleClass('hover');
      jQuery([deleter, label, link]).toggle();
    }).css({
      background: 'url("' + thumbnailUrl + '") center center no-repeat',
      width: size,
      height: size
    }).data('id', key);

    var label = jQuery('<span class="resource-label">').css('width', size)
        .text(name).appendTo(block).hide();
    var deleter = jQuery('<span>').attr({
      'class': 'resource-delete',
      title: 'Delete'
    }).click(layermanager.resource.destroy).appendTo(block).hide();

    if (type == 'image') {
      var link_class = 'resource-view-link';
    } else {
      var link_class = 'resource-download-link';
    }
    if (type == 'model') {
      var url_suffix = '.dae';
    } else if (type == 'model_in_kmz') {
      var url_suffix = '.kmz';
    } else {
      var url_suffix = '';
    }
    var link = jQuery('<a>').attr({
      'class': link_class,
      href: fullsizeUrl + url_suffix,
      target: '_blank',
      title: type == 'image' ? 'Full size' : 'Download'
    }).hide().appendTo(block).hide();

    list.append(block);
  });
};

/** Creates a new resource based on the values of the form. */
layermanager.resource.create = function() {
  var button = jQuery('#create_button');
  var form = jQuery('#resource_form form');
  var type = jQuery('#type').val();
  var name = jQuery('#filename').val();

  // TODO: If URL is provided and type is image or icon, try to validate
  //   it by creating an Image and waiting for an error or load callback.
  form.ajaxSubmit({
    iframe: true,
    beforeSubmit: function() {
      if (type == 'model_in_kmz' && name.slice(-4) != '.dae') {
        var message = 'You are creating a resource for a model packed into a ' +
                      'KMZ file. For this to work, the specified filename ' +
                      'must be the actual name of the model file inside the ' +
                      'KMZ file (including its path). The filename you ' +
                      'specified does not appear to be valid.\n\n' +
                      'Do you still want to proceed?';
        var result = confirm(message);
        if (!result) return false;
      }
      button.val('Uploading...').attr('disabled', true);
    },
    success: function(response) {
      button.val('Upload').attr('disabled', false);
      var responseParts = response.split('\n');
      var status = responseParts[0];
      var resultId = responseParts[1];
      var errorMessage = responseParts[2];
      var newUploadUrl = responseParts[3];

      // Chrome on Windows seems to insert an auto-generated <div> at the end
      // of the response (perhaps because it's sent into an empty iframe). We
      // have to cut that out.
      newUploadUrl = newUploadUrl.replace(/<div\b[^]*$/, '');

      form.attr('action', newUploadUrl);
      if (status >= 200 && status < 300) {
        if (!layermanager.resources.layer.autoManaged) {
          layermanager.resources.files[type][resultId] = name;
          layermanager.resource.refreshList();
        }
        jQuery('#file,#url,#filename').val('');
      } else {
        layermanager.ui.reportError(errorMessage);
      }
    }
  });
};

/**
 * Switches between a file upload and a URL entry field depending on the value
 * of the source dropdown.
 */
layermanager.resource.refreshSourceInput = function() {
  if (jQuery('#source').val() == 'file') {
    jQuery('#file').attr('name', 'file').show();
    jQuery('#url').attr('name', '').hide();
  } else {
    jQuery('#file').attr('name', '').hide();
    jQuery('#url').attr('name', 'url').show();
  }
};

/**
 * Guesses the file type from its extension and fills in the type and name
 * fields based on the guess.
 */
layermanager.resource.guessFileType = function() {
  var filename = jQuery('#file').val();
  var extension = filename.match(/\.(\w{3,4}$)/);
  if (extension) extension = extension[1].toLowerCase();

  if (extension == 'kmz') {
    jQuery('#filename').val('mesh.dae');
    jQuery('#type').val('model_in_kmz');
  } else {
    if (extension == 'dae') {
      jQuery('#type').val('model');
    } else if ((extension == 'jpg' || extension == 'png') &&
               jQuery('#type').val() != 'icon') {
      jQuery('#type').val('image');
    }
    jQuery('#filename').val(jQuery('#file').val());
  }
};

/** Loads the forms plugin and sets up togglers and event handlers. */
layermanager.resource.initialize = function() {
  _loadjQueryFormPlugin();
  layermanager.ui.setupTogglers();

  jQuery('#create_button').click(layermanager.resource.create);
  jQuery('#source').change(layermanager.resource.refreshSourceInput).change();
  jQuery('#file').change(layermanager.resource.guessFileType);

  var type_dropdown = jQuery('#resource_list_type');
  type_dropdown.change(layermanager.resource.refreshList).change();
};

google.setOnLoadCallback(layermanager.resource.initialize);
