'use strict';

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

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

var _index2 = _interopRequireDefault(_index);

var _obj = require('../obj.js');

var _obj2 = _interopRequireDefault(_obj);

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

var _state2 = _interopRequireDefault(_state);

var _xyz = require('../source/xyz.js');

var _xyz2 = _interopRequireDefault(_xyz);

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

/**
 * @classdesc
 * Layer source for the CartoDB Maps API.
 *
 * @constructor
 * @extends {ol.source.XYZ}
 * @param {olx.source.CartoDBOptions} options CartoDB options.
 * @api
 */
var _ol_source_CartoDB_ = function (options) {

  /**
   * @type {string}
   * @private
   */
  this.account_ = options.account;

  /**
   * @type {string}
   * @private
   */
  this.mapId_ = options.map || '';

  /**
   * @type {!Object}
   * @private
   */
  this.config_ = options.config || {};

  /**
   * @type {!Object.<string, CartoDBLayerInfo>}
   * @private
   */
  this.templateCache_ = {};

  _xyz2.default.call(this, {
    attributions: options.attributions,
    cacheSize: options.cacheSize,
    crossOrigin: options.crossOrigin,
    logo: options.logo,
    maxZoom: options.maxZoom !== undefined ? options.maxZoom : 18,
    minZoom: options.minZoom,
    projection: options.projection,
    state: _state2.default.LOADING,
    wrapX: options.wrapX
  });
  this.initializeMap_();
};

_index2.default.inherits(_ol_source_CartoDB_, _xyz2.default);

/**
 * Returns the current config.
 * @return {!Object} The current configuration.
 * @api
 */
_ol_source_CartoDB_.prototype.getConfig = function () {
  return this.config_;
};

/**
 * Updates the carto db config.
 * @param {Object} config a key-value lookup. Values will replace current values
 *     in the config.
 * @api
 */
_ol_source_CartoDB_.prototype.updateConfig = function (config) {
  _obj2.default.assign(this.config_, config);
  this.initializeMap_();
};

/**
 * Sets the CartoDB config
 * @param {Object} config In the case of anonymous maps, a CartoDB configuration
 *     object.
 * If using named maps, a key-value lookup with the template parameters.
 * @api
 */
_ol_source_CartoDB_.prototype.setConfig = function (config) {
  this.config_ = config || {};
  this.initializeMap_();
};

/**
 * Issue a request to initialize the CartoDB map.
 * @private
 */
_ol_source_CartoDB_.prototype.initializeMap_ = function () {
  var paramHash = JSON.stringify(this.config_);
  if (this.templateCache_[paramHash]) {
    this.applyTemplate_(this.templateCache_[paramHash]);
    return;
  }
  var mapUrl = 'https://' + this.account_ + '.carto.com/api/v1/map';

  if (this.mapId_) {
    mapUrl += '/named/' + this.mapId_;
  }

  var client = new XMLHttpRequest();
  client.addEventListener('load', this.handleInitResponse_.bind(this, paramHash));
  client.addEventListener('error', this.handleInitError_.bind(this));
  client.open('POST', mapUrl);
  client.setRequestHeader('Content-type', 'application/json');
  client.send(JSON.stringify(this.config_));
};

/**
 * Handle map initialization response.
 * @param {string} paramHash a hash representing the parameter set that was used
 *     for the request
 * @param {Event} event Event.
 * @private
 */
_ol_source_CartoDB_.prototype.handleInitResponse_ = function (paramHash, 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 {CartoDBLayerInfo} */JSON.parse(client.responseText);
    } catch (err) {
      this.setState(_state2.default.ERROR);
      return;
    }
    this.applyTemplate_(response);
    this.templateCache_[paramHash] = response;
    this.setState(_state2.default.READY);
  } else {
    this.setState(_state2.default.ERROR);
  }
};

/**
 * @private
 * @param {Event} event Event.
 */
_ol_source_CartoDB_.prototype.handleInitError_ = function (event) {
  this.setState(_state2.default.ERROR);
};

/**
 * Apply the new tile urls returned by carto db
 * @param {CartoDBLayerInfo} data Result of carto db call.
 * @private
 */
_ol_source_CartoDB_.prototype.applyTemplate_ = function (data) {
  var tilesUrl = 'https://' + data.cdn_url.https + '/' + this.account_ + '/api/v1/map/' + data.layergroupid + '/{z}/{x}/{y}.png';
  this.setUrl(tilesUrl);
};
exports.default = _ol_source_CartoDB_;
module.exports = exports['default'];