'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _index = require('../index.js');

var _index2 = _interopRequireDefault(_index);

var _imagecanvas = require('../imagecanvas.js');

var _imagecanvas2 = _interopRequireDefault(_imagecanvas);

var _extent = require('../extent.js');

var _extent2 = _interopRequireDefault(_extent);

var _image = require('../source/image.js');

var _image2 = _interopRequireDefault(_image);

function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : { default: obj };
}

/**
 * @classdesc
 * Base class for image sources where a canvas element is the image.
 *
 * @constructor
 * @extends {ol.source.Image}
 * @param {olx.source.ImageCanvasOptions} options Constructor options.
 * @api
 */
var _ol_source_ImageCanvas_ = function (options) {

  _image2.default.call(this, {
    attributions: options.attributions,
    logo: options.logo,
    projection: options.projection,
    resolutions: options.resolutions,
    state: options.state
  });

  /**
   * @private
   * @type {ol.CanvasFunctionType}
   */
  this.canvasFunction_ = options.canvasFunction;

  /**
   * @private
   * @type {ol.ImageCanvas}
   */
  this.canvas_ = null;

  /**
   * @private
   * @type {number}
   */
  this.renderedRevision_ = 0;

  /**
   * @private
   * @type {number}
   */
  this.ratio_ = options.ratio !== undefined ? options.ratio : 1.5;
};

_index2.default.inherits(_ol_source_ImageCanvas_, _image2.default);

/**
 * @inheritDoc
 */
_ol_source_ImageCanvas_.prototype.getImageInternal = function (extent, resolution, pixelRatio, projection) {
  resolution = this.findNearestResolution(resolution);

  var canvas = this.canvas_;
  if (canvas && this.renderedRevision_ == this.getRevision() && canvas.getResolution() == resolution && canvas.getPixelRatio() == pixelRatio && _extent2.default.containsExtent(canvas.getExtent(), extent)) {
    return canvas;
  }

  extent = extent.slice();
  _extent2.default.scaleFromCenter(extent, this.ratio_);
  var width = _extent2.default.getWidth(extent) / resolution;
  var height = _extent2.default.getHeight(extent) / resolution;
  var size = [width * pixelRatio, height * pixelRatio];

  var canvasElement = this.canvasFunction_(extent, resolution, pixelRatio, size, projection);
  if (canvasElement) {
    canvas = new _imagecanvas2.default(extent, resolution, pixelRatio, canvasElement);
  }
  this.canvas_ = canvas;
  this.renderedRevision_ = this.getRevision();

  return canvas;
};
exports.default = _ol_source_ImageCanvas_;
module.exports = exports['default'];