'use strict';

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

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

var _index2 = _interopRequireDefault(_index);

var _tileurlfunction = require('../tileurlfunction.js');

var _tileurlfunction2 = _interopRequireDefault(_tileurlfunction);

var _asserts = require('../asserts.js');

var _asserts2 = _interopRequireDefault(_asserts);

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

var _extent2 = _interopRequireDefault(_extent);

var _net = require('../net.js');

var _net2 = _interopRequireDefault(_net);

var _proj = require('../proj.js');

var _proj2 = _interopRequireDefault(_proj);

var _state = require('../source/state.js');

var _state2 = _interopRequireDefault(_state);

var _tileimage = require('../source/tileimage.js');

var _tileimage2 = _interopRequireDefault(_tileimage);

var _tilegrid = require('../tilegrid.js');

var _tilegrid2 = _interopRequireDefault(_tilegrid);

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

/**
 * @classdesc
 * Layer source for tile data in TileJSON format.
 *
 * @constructor
 * @extends {ol.source.TileImage}
 * @param {olx.source.TileJSONOptions} options TileJSON options.
 * @api
 */
var _ol_source_TileJSON_ = function (options) {

  /**
   * @type {TileJSON}
   * @private
   */
  this.tileJSON_ = null;

  _tileimage2.default.call(this, {
    attributions: options.attributions,
    cacheSize: options.cacheSize,
    crossOrigin: options.crossOrigin,
    projection: _proj2.default.get('EPSG:3857'),
    reprojectionErrorThreshold: options.reprojectionErrorThreshold,
    state: _state2.default.LOADING,
    tileLoadFunction: options.tileLoadFunction,
    wrapX: options.wrapX !== undefined ? options.wrapX : true,
    transition: options.transition
  });

  if (options.url) {
    if (options.jsonp) {
      _net2.default.jsonp(options.url, this.handleTileJSONResponse.bind(this), this.handleTileJSONError.bind(this));
    } else {
      var client = new XMLHttpRequest();
      client.addEventListener('load', this.onXHRLoad_.bind(this));
      client.addEventListener('error', this.onXHRError_.bind(this));
      client.open('GET', options.url);
      client.send();
    }
  } else if (options.tileJSON) {
    this.handleTileJSONResponse(options.tileJSON);
  } else {
    _asserts2.default.assert(false, 51); // Either `url` or `tileJSON` options must be provided
  }
}; // FIXME check order of async callbacks

/**
 * @see http://mapbox.com/developers/api/
 */

_index2.default.inherits(_ol_source_TileJSON_, _tileimage2.default);

/**
 * @private
 * @param {Event} event The load event.
 */
_ol_source_TileJSON_.prototype.onXHRLoad_ = function (event) {
  var client = /** @type {XMLHttpRequest} */event.target;
  // status will be 0 for file:// urls
  if (!client.status || client.status >= 200 && client.status < 300) {
    var response;
    try {
      response = /** @type {TileJSON} */JSON.parse(client.responseText);
    } catch (err) {
      this.handleTileJSONError();
      return;
    }
    this.handleTileJSONResponse(response);
  } else {
    this.handleTileJSONError();
  }
};

/**
 * @private
 * @param {Event} event The error event.
 */
_ol_source_TileJSON_.prototype.onXHRError_ = function (event) {
  this.handleTileJSONError();
};

/**
 * @return {TileJSON} The tilejson object.
 * @api
 */
_ol_source_TileJSON_.prototype.getTileJSON = function () {
  return this.tileJSON_;
};

/**
 * @protected
 * @param {TileJSON} tileJSON Tile JSON.
 */
_ol_source_TileJSON_.prototype.handleTileJSONResponse = function (tileJSON) {

  var epsg4326Projection = _proj2.default.get('EPSG:4326');

  var sourceProjection = this.getProjection();
  var extent;
  if (tileJSON.bounds !== undefined) {
    var transform = _proj2.default.getTransformFromProjections(epsg4326Projection, sourceProjection);
    extent = _extent2.default.applyTransform(tileJSON.bounds, transform);
  }

  var minZoom = tileJSON.minzoom || 0;
  var maxZoom = tileJSON.maxzoom || 22;
  var tileGrid = _tilegrid2.default.createXYZ({
    extent: _tilegrid2.default.extentFromProjection(sourceProjection),
    maxZoom: maxZoom,
    minZoom: minZoom
  });
  this.tileGrid = tileGrid;

  this.tileUrlFunction = _tileurlfunction2.default.createFromTemplates(tileJSON.tiles, tileGrid);

  if (tileJSON.attribution !== undefined && !this.getAttributions2()) {
    var attributionExtent = extent !== undefined ? extent : epsg4326Projection.getExtent();

    this.setAttributions(function (frameState) {
      if (_extent2.default.intersects(attributionExtent, frameState.extent)) {
        return [tileJSON.attribution];
      }
      return null;
    });
  }
  this.tileJSON_ = tileJSON;
  this.setState(_state2.default.READY);
};

/**
 * @protected
 */
_ol_source_TileJSON_.prototype.handleTileJSONError = function () {
  this.setState(_state2.default.ERROR);
};
exports.default = _ol_source_TileJSON_;
module.exports = exports['default'];