'use strict';

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

/**
 * @param {number} z Z.
 * @param {number} x X.
 * @param {number} y Y.
 * @param {ol.TileCoord=} opt_tileCoord Tile coordinate.
 * @return {ol.TileCoord} Tile coordinate.
 */
_ol_tilecoord_.createOrUpdate = function (z, x, y, opt_tileCoord) {
  if (opt_tileCoord !== undefined) {
    opt_tileCoord[0] = z;
    opt_tileCoord[1] = x;
    opt_tileCoord[2] = y;
    return opt_tileCoord;
  } else {
    return [z, x, y];
  }
};

/**
 * @param {number} z Z.
 * @param {number} x X.
 * @param {number} y Y.
 * @return {string} Key.
 */
_ol_tilecoord_.getKeyZXY = function (z, x, y) {
  return z + '/' + x + '/' + y;
};

/**
 * Get the key for a tile coord.
 * @param {ol.TileCoord} tileCoord The tile coord.
 * @return {string} Key.
 */
_ol_tilecoord_.getKey = function (tileCoord) {
  return _ol_tilecoord_.getKeyZXY(tileCoord[0], tileCoord[1], tileCoord[2]);
};

/**
 * Get a tile coord given a key.
 * @param {string} key The tile coord key.
 * @return {ol.TileCoord} The tile coord.
 */
_ol_tilecoord_.fromKey = function (key) {
  return key.split('/').map(Number);
};

/**
 * @param {ol.TileCoord} tileCoord Tile coord.
 * @return {number} Hash.
 */
_ol_tilecoord_.hash = function (tileCoord) {
  return (tileCoord[1] << tileCoord[0]) + tileCoord[2];
};

/**
 * @param {ol.TileCoord} tileCoord Tile coord.
 * @return {string} Quad key.
 */
_ol_tilecoord_.quadKey = function (tileCoord) {
  var z = tileCoord[0];
  var digits = new Array(z);
  var mask = 1 << z - 1;
  var i, charCode;
  for (i = 0; i < z; ++i) {
    // 48 is charCode for 0 - '0'.charCodeAt(0)
    charCode = 48;
    if (tileCoord[1] & mask) {
      charCode += 1;
    }
    if (tileCoord[2] & mask) {
      charCode += 2;
    }
    digits[i] = String.fromCharCode(charCode);
    mask >>= 1;
  }
  return digits.join('');
};

/**
 * @param {ol.TileCoord} tileCoord Tile coordinate.
 * @param {!ol.tilegrid.TileGrid} tileGrid Tile grid.
 * @return {boolean} Tile coordinate is within extent and zoom level range.
 */
_ol_tilecoord_.withinExtentAndZ = function (tileCoord, tileGrid) {
  var z = tileCoord[0];
  var x = tileCoord[1];
  var y = tileCoord[2];

  if (tileGrid.getMinZoom() > z || z > tileGrid.getMaxZoom()) {
    return false;
  }
  var extent = tileGrid.getExtent();
  var tileRange;
  if (!extent) {
    tileRange = tileGrid.getFullTileRange(z);
  } else {
    tileRange = tileGrid.getTileRangeForExtentAndZ(extent, z);
  }
  if (!tileRange) {
    return true;
  } else {
    return tileRange.containsXY(x, y);
  }
};
exports.default = _ol_tilecoord_;
module.exports = exports['default'];