'use strict';

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

var _regenerator = require('babel-runtime/regenerator');

var _regenerator2 = _interopRequireDefault(_regenerator);

var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');

var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _assign = require('lodash/assign');

var _assign2 = _interopRequireDefault(_assign);

var _methodsUtil = require('../../../_util/methods-util');

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

var _wmts = require('./wmts');

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

/**
 * 解析Arcgis WMTS类型的服务地址获取图层服务数据信息
 */
/**
 * @文件说明: Services.ArcgisWMTS - Arcgis WMTS服务
 * @创建人: pjtools@vip.qq.com
 * @创建时间: 2020-03-25 21:04:08
 */

var fetchWMTSCapabilities = function fetchWMTSCapabilities(own, url, options) {
  var GeoGlobe = own.exports.GeoGlobe;

  var isProxyUrl = (0, _methodsUtil.isBooleanFlase)(options.proxy) ? false : true;

  return new Promise(function (resolve, reject) {
    var urlParams = '';
    var capabilitiesUrl = url;
    if (url.indexOf('?') !== -1) {
      var urlSplit = url.split('?');
      capabilitiesUrl = urlSplit[0];
      urlParams = urlSplit[1];
    }
    capabilitiesUrl += '/WMTS/1.0.0/WMTSCapabilities.xml';
    urlParams && (capabilitiesUrl += '?' + urlParams);
    isProxyUrl && (capabilitiesUrl = '' + own.proxyURL + capabilitiesUrl);

    // 请求图层数据信息
    var errorMsg = 'ArcgisWMTS\u670D\u52A1\u5730\u5740[ ' + url + ' ]\u6570\u636E\u89E3\u6790\u5931\u8D25.';
    GeoGlobe.Request.GET({
      url: capabilitiesUrl,
      success: function success(data) {
        var opts = {};
        try {
          // 获取Arcgis WMTS服务的Capabilities信息
          var capabilities = !data.responseXML || !data.responseXML.documentElement ? data.responseText : data.responseXML;
          capabilities = new GeoGlobe.Format.WMTSCapabilities.v1_0_0().read(capabilities);
          var wmtsOpts = (0, _wmts.getWMTSCapabilities)(capabilities, options, GeoGlobe);
          if (wmtsOpts) {
            opts = (0, _assign2['default'])({}, opts, wmtsOpts);
            // 矩形范围
            var defaultLayer = capabilities.contents.layers && capabilities.contents.layers[0];
            var bounding = defaultLayer.bounds;
            var defaultBounds = [[Number(bounding._sw.lat), Number(bounding._sw.lng)], [Number(bounding._ne.lat), Number(bounding._ne.lng)]];
            opts.tileBBox = defaultBounds;
          } else {
            console.error(errorMsg);
            reject();
          }
        } catch (e) {
          console.error(errorMsg);
          reject();
        }
        resolve(opts);
      },
      failure: function failure() {
        console.error(errorMsg);
        reject();
      }
    });
  });
};

var ArcgisWMTS = function () {
  function ArcgisWMTS(iMapApi) {
    (0, _classCallCheck3['default'])(this, ArcgisWMTS);

    this.iMapApi = iMapApi;
    this.exports = iMapApi && iMapApi.exports ? iMapApi.exports : {};
    this.proxyURL = iMapApi.proxyURL || '';
    this.options = (0, _extends3['default'])({}, _index.defaultServicesSourceOptions, _index.defaultServicesLayerOptions, _wmts.defaultServicesOptions);
  }

  /**
   * 获取解析Arcgis WMTS服务的图层对象
   * @param {String} id 图层Id名称
   * @param {String} name 图层Name名
   * @param {String} url 服务地址
   * @param {Object} options 解析服务的参数选项
   */


  (0, _createClass3['default'])(ArcgisWMTS, [{
    key: 'getLayer',
    value: function () {
      var _ref = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function _callee(id) {
        var name = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
        var url = arguments[2];
        var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
        var opts, layerOptions, layer, urlParams, wmtsUrl, urlSplit;
        return _regenerator2['default'].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                opts = (0, _assign2['default'])(this.options, options);
                // 获取服务信息

                _context.next = 3;
                return fetchWMTSCapabilities(this, url, opts);

              case 3:
                layerOptions = _context.sent;

                // 获取Arcgis WMTS图层
                layer = (0, _wmts.fetchWMTSLayerStyles)(this, id, url, layerOptions, (0, _extends3['default'])({}, opts, { name: name }));

                layer.metadata.serviceType = 'ArcgisWMTS';
                // 计算Arcgis WMTS的数据源地址
                urlParams = '';
                wmtsUrl = url;

                if (url.indexOf('?') !== -1) {
                  urlSplit = url.split('?');

                  wmtsUrl = urlSplit[0];
                  urlParams = urlSplit[1];
                }
                wmtsUrl += '/WMTS/tile/' + layerOptions.version + '/' + layerOptions.layerName + '/' + layerOptions.styleName + '/' + layerOptions.matrixSet + '/{z}/{y}/{x}.png';
                urlParams && (wmtsUrl += '?' + urlParams);
                !(0, _methodsUtil.isBooleanFlase)(opts.proxy) && (wmtsUrl = '' + this.proxyURL + wmtsUrl);
                layer.source.tiles = [wmtsUrl];
                return _context.abrupt('return', layer);

              case 14:
              case 'end':
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function getLayer(_x3) {
        return _ref.apply(this, arguments);
      }

      return getLayer;
    }()
  }]);
  return ArcgisWMTS;
}();

exports['default'] = ArcgisWMTS;