'use strict';

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

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

var _index2 = _interopRequireDefault(_index);

var _tile = require('../tile.js');

var _tile2 = _interopRequireDefault(_tile);

var _tilestate = require('../tilestate.js');

var _tilestate2 = _interopRequireDefault(_tilestate);

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

var _tileurlfunction2 = _interopRequireDefault(_tileurlfunction);

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

var _asserts2 = _interopRequireDefault(_asserts);

var _events = require('../events.js');

var _events2 = _interopRequireDefault(_events);

var _eventtype = require('../events/eventtype.js');

var _eventtype2 = _interopRequireDefault(_eventtype);

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 _tile3 = require('../source/tile.js');

var _tile4 = _interopRequireDefault(_tile3);

var _tilecoord = require('../tilecoord.js');

var _tilecoord2 = _interopRequireDefault(_tilecoord);

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

var _tilegrid2 = _interopRequireDefault(_tilegrid);

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

/**
 * @classdesc
 * Layer source for UTFGrid interaction data loaded from TileJSON format.
 *
 * @constructor
 * @extends {ol.source.Tile}
 * @param {olx.source.TileUTFGridOptions} options Source options.
 * @api
 */
var _ol_source_TileUTFGrid_ = function (options) {
  _tile4.default.call(this, {
    projection: _proj2.default.get('EPSG:3857'),
    state: _state2.default.LOADING
  });

  /**
   * @private
   * @type {boolean}
   */
  this.preemptive_ = options.preemptive !== undefined ? options.preemptive : true;

  /**
   * @private
   * @type {!ol.TileUrlFunctionType}
   */
  this.tileUrlFunction_ = _tileurlfunction2.default.nullTileUrlFunction;

  /**
   * @private
   * @type {string|undefined}
   */
  this.template_ = undefined;

  /**
   * @private
   * @type {boolean}
   */
  this.jsonp_ = options.jsonp || false;

  if (options.url) {
    if (this.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
  }
};

_index2.default.inherits(_ol_source_TileUTFGrid_, _tile4.default);

/**
 * @private
 * @param {Event} event The load event.
 */
_ol_source_TileUTFGrid_.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_TileUTFGrid_.prototype.onXHRError_ = function (event) {
  this.handleTileJSONError();
};

/**
 * Return the template from TileJSON.
 * @return {string|undefined} The template from TileJSON.
 * @api
 */
_ol_source_TileUTFGrid_.prototype.getTemplate = function () {
  return this.template_;
};

/**
 * Calls the callback (synchronously by default) with the available data
 * for given coordinate and resolution (or `null` if not yet loaded or
 * in case of an error).
 * @param {ol.Coordinate} coordinate Coordinate.
 * @param {number} resolution Resolution.
 * @param {function(this: T, *)} callback Callback.
 * @param {T=} opt_this The object to use as `this` in the callback.
 * @param {boolean=} opt_request If `true` the callback is always async.
 *                               The tile data is requested if not yet loaded.
 * @template T
 * @api
 */
_ol_source_TileUTFGrid_.prototype.forDataAtCoordinateAndResolution = function (coordinate, resolution, callback, opt_this, opt_request) {
  if (this.tileGrid) {
    var tileCoord = this.tileGrid.getTileCoordForCoordAndResolution(coordinate, resolution);
    var tile = /** @type {!ol.source.TileUTFGrid.Tile_} */this.getTile(tileCoord[0], tileCoord[1], tileCoord[2], 1, this.getProjection());
    tile.forDataAtCoordinate(coordinate, callback, opt_this, opt_request);
  } else {
    if (opt_request === true) {
      setTimeout(function () {
        callback.call(opt_this, null);
      }, 0);
    } else {
      callback.call(opt_this, null);
    }
  }
};

/**
 * @protected
 */
_ol_source_TileUTFGrid_.prototype.handleTileJSONError = function () {
  this.setState(_state2.default.ERROR);
};

/**
 * TODO: very similar to ol.source.TileJSON#handleTileJSONResponse
 * @protected
 * @param {TileJSON} tileJSON Tile JSON.
 */
_ol_source_TileUTFGrid_.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.template_ = tileJSON.template;

  var grids = tileJSON.grids;
  if (!grids) {
    this.setState(_state2.default.ERROR);
    return;
  }

  this.tileUrlFunction_ = _tileurlfunction2.default.createFromTemplates(grids, tileGrid);

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

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

  this.setState(_state2.default.READY);
};

/**
 * @inheritDoc
 */
_ol_source_TileUTFGrid_.prototype.getTile = function (z, x, y, pixelRatio, projection) {
  var tileCoordKey = _tilecoord2.default.getKeyZXY(z, x, y);
  if (this.tileCache.containsKey(tileCoordKey)) {
    return (/** @type {!ol.Tile} */this.tileCache.get(tileCoordKey)
    );
  } else {
    var tileCoord = [z, x, y];
    var urlTileCoord = this.getTileCoordForTileUrlFunction(tileCoord, projection);
    var tileUrl = this.tileUrlFunction_(urlTileCoord, pixelRatio, projection);
    var tile = new _ol_source_TileUTFGrid_.Tile_(tileCoord, tileUrl !== undefined ? _tilestate2.default.IDLE : _tilestate2.default.EMPTY, tileUrl !== undefined ? tileUrl : '', this.tileGrid.getTileCoordExtent(tileCoord), this.preemptive_, this.jsonp_);
    this.tileCache.set(tileCoordKey, tile);
    return tile;
  }
};

/**
 * @inheritDoc
 */
_ol_source_TileUTFGrid_.prototype.useTile = function (z, x, y) {
  var tileCoordKey = _tilecoord2.default.getKeyZXY(z, x, y);
  if (this.tileCache.containsKey(tileCoordKey)) {
    this.tileCache.get(tileCoordKey);
  }
};

/**
 * @constructor
 * @extends {ol.Tile}
 * @param {ol.TileCoord} tileCoord Tile coordinate.
 * @param {ol.TileState} state State.
 * @param {string} src Image source URI.
 * @param {ol.Extent} extent Extent of the tile.
 * @param {boolean} preemptive Load the tile when visible (before it's needed).
 * @param {boolean} jsonp Load the tile as a script.
 * @private
 */
_ol_source_TileUTFGrid_.Tile_ = function (tileCoord, state, src, extent, preemptive, jsonp) {

  _tile2.default.call(this, tileCoord, state);

  /**
   * @private
   * @type {string}
   */
  this.src_ = src;

  /**
   * @private
   * @type {ol.Extent}
   */
  this.extent_ = extent;

  /**
   * @private
   * @type {boolean}
   */
  this.preemptive_ = preemptive;

  /**
   * @private
   * @type {Array.<string>}
   */
  this.grid_ = null;

  /**
   * @private
   * @type {Array.<string>}
   */
  this.keys_ = null;

  /**
   * @private
   * @type {Object.<string, Object>|undefined}
   */
  this.data_ = null;

  /**
   * @private
   * @type {boolean}
   */
  this.jsonp_ = jsonp;
};
_index2.default.inherits(_ol_source_TileUTFGrid_.Tile_, _tile2.default);

/**
 * Get the image element for this tile.
 * @return {Image} Image.
 */
_ol_source_TileUTFGrid_.Tile_.prototype.getImage = function () {
  return null;
};

/**
 * Synchronously returns data at given coordinate (if available).
 * @param {ol.Coordinate} coordinate Coordinate.
 * @return {*} The data.
 */
_ol_source_TileUTFGrid_.Tile_.prototype.getData = function (coordinate) {
  if (!this.grid_ || !this.keys_) {
    return null;
  }
  var xRelative = (coordinate[0] - this.extent_[0]) / (this.extent_[2] - this.extent_[0]);
  var yRelative = (coordinate[1] - this.extent_[1]) / (this.extent_[3] - this.extent_[1]);

  var row = this.grid_[Math.floor((1 - yRelative) * this.grid_.length)];

  if (typeof row !== 'string') {
    return null;
  }

  var code = row.charCodeAt(Math.floor(xRelative * row.length));
  if (code >= 93) {
    code--;
  }
  if (code >= 35) {
    code--;
  }
  code -= 32;

  var data = null;
  if (code in this.keys_) {
    var id = this.keys_[code];
    if (this.data_ && id in this.data_) {
      data = this.data_[id];
    } else {
      data = id;
    }
  }
  return data;
};

/**
 * Calls the callback (synchronously by default) with the available data
 * for given coordinate (or `null` if not yet loaded).
 * @param {ol.Coordinate} coordinate Coordinate.
 * @param {function(this: T, *)} callback Callback.
 * @param {T=} opt_this The object to use as `this` in the callback.
 * @param {boolean=} opt_request If `true` the callback is always async.
 *                               The tile data is requested if not yet loaded.
 * @template T
 */
_ol_source_TileUTFGrid_.Tile_.prototype.forDataAtCoordinate = function (coordinate, callback, opt_this, opt_request) {
  if (this.state == _tilestate2.default.IDLE && opt_request === true) {
    _events2.default.listenOnce(this, _eventtype2.default.CHANGE, function (e) {
      callback.call(opt_this, this.getData(coordinate));
    }, this);
    this.loadInternal_();
  } else {
    if (opt_request === true) {
      setTimeout(function () {
        callback.call(opt_this, this.getData(coordinate));
      }.bind(this), 0);
    } else {
      callback.call(opt_this, this.getData(coordinate));
    }
  }
};

/**
 * @inheritDoc
 */
_ol_source_TileUTFGrid_.Tile_.prototype.getKey = function () {
  return this.src_;
};

/**
 * @private
 */
_ol_source_TileUTFGrid_.Tile_.prototype.handleError_ = function () {
  this.state = _tilestate2.default.ERROR;
  this.changed();
};

/**
 * @param {!UTFGridJSON} json UTFGrid data.
 * @private
 */
_ol_source_TileUTFGrid_.Tile_.prototype.handleLoad_ = function (json) {
  this.grid_ = json.grid;
  this.keys_ = json.keys;
  this.data_ = json.data;

  this.state = _tilestate2.default.EMPTY;
  this.changed();
};

/**
 * @private
 */
_ol_source_TileUTFGrid_.Tile_.prototype.loadInternal_ = function () {
  if (this.state == _tilestate2.default.IDLE) {
    this.state = _tilestate2.default.LOADING;
    if (this.jsonp_) {
      _net2.default.jsonp(this.src_, this.handleLoad_.bind(this), this.handleError_.bind(this));
    } else {
      var client = new XMLHttpRequest();
      client.addEventListener('load', this.onXHRLoad_.bind(this));
      client.addEventListener('error', this.onXHRError_.bind(this));
      client.open('GET', this.src_);
      client.send();
    }
  }
};

/**
 * @private
 * @param {Event} event The load event.
 */
_ol_source_TileUTFGrid_.Tile_.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 {!UTFGridJSON} */JSON.parse(client.responseText);
    } catch (err) {
      this.handleError_();
      return;
    }
    this.handleLoad_(response);
  } else {
    this.handleError_();
  }
};

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

/**
 * @override
 */
_ol_source_TileUTFGrid_.Tile_.prototype.load = function () {
  if (this.preemptive_) {
    this.loadInternal_();
  }
};
exports.default = _ol_source_TileUTFGrid_;
module.exports = exports['default'];