/*
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * 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.
 */
'use strict';


var eventEmitter = require('minimal-event-emitter');
var extend = require('./util/extend');


/**
 * @class
 * @classdesc A Layer is a combination of {@link Source}, {@link Geometry},
 *            {@link View} and {@link TextureStore} that can be added into a
 *            {@link Stage} and rendered with effects.
 * @param {Stage} stage
 * @param {Source} source
 * @param {Geometry} geometry
 * @param {View} view
 * @param {TextureStore} textureStore
 * @param {Object} opts
 * @param {Effects} opts.effects
*/
function Layer(stage, source, geometry, view, textureStore, opts) {

  opts = opts || {};

  var self = this;

  this._stage = stage;
  this._source = source;
  this._geometry = geometry;
  this._view = view;
  this._textureStore = textureStore;

  this._effects = opts.effects || {};

  this._fixedLevelIndex = null;

  this._viewChangeHandler = function() {
    self.emit('viewChange', self.view());
  };

  this._view.addEventListener('change', this._viewChangeHandler);

  this._textureStoreChangeHandler = function() {
    self.emit('textureStoreChange', self.textureStore());
  };

  this._textureStore.addEventListener('textureLoad',
    this._textureStoreChangeHandler);
  this._textureStore.addEventListener('textureError',
    this._textureStoreChangeHandler);
  this._textureStore.addEventListener('textureInvalid',
    this._textureStoreChangeHandler);

}

eventEmitter(Layer);


/**
 * Destructor.
 */
Layer.prototype.destroy = function() {
  this._view.removeEventListener('change', this._viewChangeHandler);
  this._textureStore.removeEventListener('textureLoad',
    this._textureStoreChangeHandler);
  this._textureStore.removeEventListener('textureError',
    this._textureStoreChangeHandler);
  this._textureStore.removeEventListener('textureInvalid',
    this._textureStoreChangeHandler);
  this._stage.removeEventListener('resize', this._handleStageResize);
  this._stage = null;
  this._source = null;
  this._geometry = null;
  this._view = null;
  this._textureStore = null;
  this._fixedLevelIndex = null;
  this._effects = null;
  this._viewChangeHandler = null;
  this._textureStoreChangeHandler = null;
};


/**
 * Get the underlying source.
 * @return {Source}
 */
Layer.prototype.source = function() {
  return this._source;
};


/**
 * Get the underlying geometry.
 * @return {Geometry}
 */
Layer.prototype.geometry = function() {
  return this._geometry;
};


/**
 * Get the underlying view.
 * @return {View}
 */
Layer.prototype.view = function() {
  return this._view;
};


/**
 * Get the underlying TextureStore.
 * @return {TextureStore}
 */
Layer.prototype.textureStore = function() {
  return this._textureStore;
};


/**
 * Get the effects.
 * @return {Effects}
 */
Layer.prototype.effects = function() {
  return this._effects;
};


/**
 * Set the underlying view.
 * @param {View} view
 */
Layer.prototype.setView = function(view) {
  this._view = view;
  this.emit('viewChange', this._view);
};


/**
 * Set the effects.
 * @param {Effects} effects
 */
Layer.prototype.setEffects = function(effects) {
  this._effects = effects;
  this.emit('effectsChange', this._effects);
};


/**
 * Merge effects into the current ones. The merge is non-recursive; for
 * instance, if current effects are `{ rect: { relativeWidth: 0.5 } }`,
 * calling this method with `{ rect: { relativeX: 0.5 }}` will reset
 * `rect.relativeWidth`.
 *
 * @param {Effects} effects
 */
Layer.prototype.mergeEffects = function(effects) {
  extend(this._effects, effects);
  this.emit('effectsChange', this._effects);
};


/**
 * Get the fixed level index.
 * @return {(number|null)}
 */
Layer.prototype.fixedLevel = function() {
  return this._fixedLevelIndex;
};


/**
 * Set the fixed level index. When set, the corresponding level will be
 * used regardless of the view parameters. Unset with a null argument.
 * @param {(number|null)} levelIndex
 */
Layer.prototype.setFixedLevel = function(levelIndex) {
  if (levelIndex !== this._fixedLevelIndex) {
    if (levelIndex != null && (levelIndex >= this._geometry.levelList.length || levelIndex < 0)) {
      throw new Error("Level index out of range: " + levelIndex);
    }
    this._fixedLevelIndex = levelIndex;
    this.emit('fixedLevelChange', this._fixedLevelIndex);
  }
};


Layer.prototype._selectLevel = function() {
  var level;
  if (this._fixedLevelIndex != null) {
    level = this._geometry.levelList[this._fixedLevelIndex];
  }
  else {
    level = this._view.selectLevel(this._geometry.selectableLevelList);
  }
  return level;
};


Layer.prototype.visibleTiles = function(result) {
  var level = this._selectLevel();
  return this._geometry.visibleTiles(this._view, level, result);
};


/**
 * Pin a whole level into the texture store.
 * @param {Number} levelIndex
 */
Layer.prototype.pinLevel = function(levelIndex) {
  var level = this._geometry.levelList[levelIndex];
  var tiles = this._geometry.levelTiles(level);
  for (var i = 0; i < tiles.length; i++) {
    this._textureStore.pin(tiles[i]);
  }
};


/**
 * Unpin a whole level from the texture store.
 * @param {Number} levelIndex
 */
Layer.prototype.unpinLevel = function(levelIndex) {
  var level = this._geometry.levelList[levelIndex];
  var tiles = this._geometry.levelTiles(level);
  for (var i = 0; i < tiles.length; i++) {
    this._textureStore.unpin(tiles[i]);
  }
};


/**
 * Pin the first level. Equivalent to `pinLevel(0)`.
 */
Layer.prototype.pinFirstLevel = function() {
  return this.pinLevel(0);
};


/**
 * Unpin the first level. Equivalent to `unpinLevel(0)`.
 */
Layer.prototype.unpinFirstLevel = function() {
  return this.unpinLevel(0);
};


module.exports = Layer;

@@ -2452,78 +2452,8 @@
 r);%0A
-  this._stage.removeEventListener('resize', this._handleStageResize);%0A
   th

Remove teardown logic for event listener that was never added.