/**
 * Copyright (c) 2022 International Business Group, Ant Group. All rights reserved.
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, and/or distribute the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 1. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE; and
 * 2. If applicable, the use of the Software is also subject to the terms and conditions of any non-disclosure agreement signed by you and the relevant Ant Group entity.
 */
function _typeof(obj) {
  '@babel/helpers - typeof';

  return _typeof = 'function' == typeof Symbol && 'symbol' == typeof Symbol.iterator ? function (obj) {
    return typeof obj;
  } : function (obj) {
    return obj && 'function' == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj;
  }, _typeof(obj);
}
function ownKeys(object, enumerableOnly) {
  var keys = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    enumerableOnly && (symbols = symbols.filter(function (sym) {
      return Object.getOwnPropertyDescriptor(object, sym).enumerable;
    })), keys.push.apply(keys, symbols);
  }
  return keys;
}
function _objectSpread(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = null != arguments[i] ? arguments[i] : {};
    i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
      _defineProperty(target, key, source[key]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
      Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
    });
  }
  return target;
}
function _defineProperty(obj, key, value) {
  key = _toPropertyKey(key);
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }
  return obj;
}
function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError('Cannot call a class as a function');
  }
}
function _defineProperties(target, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ('value' in descriptor) descriptor.writable = true;
    Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
  }
}
function _createClass(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  if (staticProps) _defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, 'prototype', {
    writable: false
  });
  return Constructor;
}
function _toPropertyKey(arg) {
  var key = _toPrimitive(arg, 'string');
  return _typeof(key) === 'symbol' ? key : String(key);
}
function _toPrimitive(input, hint) {
  if (_typeof(input) !== 'object' || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || 'default');
    if (_typeof(res) !== 'object') return res;
    throw new TypeError('@@toPrimitive must return a primitive value.');
  }
  return (hint === 'string' ? String : Number)(input);
}
import * as Browser from "./browser";
import { buildIFrame, evokeByIFrame, evokeByLocation, evokeByTagA } from "./evoke";
import { generateIntent, generateLink } from "./generate";
import { addEventListener, checkCallAppSuccess, checkIsHttpUrl } from "./utils/index";
var EvokeAppType;
(function (EvokeAppType) {
  EvokeAppType['SCHEME'] = 'Scheme';
  EvokeAppType['LINK'] = 'Link';
  EvokeAppType['INTENT'] = 'Intent';
})(EvokeAppType || (EvokeAppType = {}));
var CallApp = /*#__PURE__*/function () {
  function CallApp(config) {
    _classCallCheck(this, CallApp);
    this.config = void 0;
    this.timer = void 0;
    this.options = void 0;
    this.evokeAppBy = void 0;
    var defaultConfig = {
      delay: 0
    };
    this.config = _objectSpread(_objectSpread({}, defaultConfig), config);
    this.options = {};
    this.timer = null;
    this.evokeAppBy = {
      url: '',
      type: EvokeAppType.LINK
    };
    this.init();
  }
  _createClass(CallApp, [{
    key: 'init',
    value: function init() {
      buildIFrame();
      addEventListener({
        evokeAppBy: this.evokeAppBy,
        successCb: this.config.successCb,
        timeout: this.config.resultJudgmentTime
      });
    }
    /**
     * @param options
     */
  }, {
    key: 'open',
    value: function open(options) {
      this.options = options;
      var _this$options = this.options,
        scheme = _this$options.scheme,
        intent = _this$options.intent,
        link = _this$options.link,
        params = _this$options.params,
        fallback = _this$options.fallback;
      if (!scheme && !link && !intent) {
        console.error('请至少填一个链接');
        return;
      }
      if (link && checkIsHttpUrl(link)) {
        this.options.link = generateLink(link, params);
        this.handleLink();
      } else if (scheme && !checkIsHttpUrl(scheme)) {
        this.options.scheme = generateLink(scheme, params);
        this.handleScheme();
      } else if (intent && intent.scheme && intent.package) {
        this.handleIntent();
      } else if (fallback) {
        fallback();
      } else {
        console.error('唤端失败');
      }
    }
  }, {
    key: 'handleLink',
    value: function handleLink() {
      this.evokeAppBy.type = EvokeAppType.LINK;
      var _this$options2 = this.options,
        link = _this$options2.link,
        scheme = _this$options2.scheme,
        delay = _this$options2.delay,
        fallback = _this$options2.fallback;
      if (Browser.isIOS) {
        if (Browser.getIOSVersion() > 9) {
          this.evokeByLocationDelay(link, delay, fallback, this.handleScheme);
        } else if (scheme) {
          this.handleScheme();
        } else if (fallback) {
          fallback();
        } else {
          console.error('唤端失败');
        }
      } else {
        this.evokeByLocationDelay(link, delay, fallback, this.handleScheme);
      }
    }
  }, {
    key: 'handleIntent',
    value: function handleIntent() {
      this.evokeAppBy.type = EvokeAppType.INTENT;
      var _this$options3 = this.options,
        intent = _this$options3.intent,
        delay = _this$options3.delay,
        fallback = _this$options3.fallback;
      if (intent && intent.scheme && intent.package) {
        this.evokeByLocationDelay(generateIntent(intent.scheme, intent.package, intent.fallbackUrl), delay, fallback);
      }
    }
  }, {
    key: 'handleScheme',
    value: function handleScheme() {
      this.evokeAppBy.type = EvokeAppType.SCHEME;
      var _this$options4 = this.options,
        scheme = _this$options4.scheme,
        delay = _this$options4.delay,
        fallback = _this$options4.fallback;
      if (scheme) {
        if (Browser.isIOS) {
          this.handleIOSScheme();
        } else if (Browser.isOriginalChrome || Browser.isFirefox) {
          this.handleOriginalChrome();
        } else {
          this.evokeByIFrameDelay(scheme, delay, fallback);
        }
      }
    }
  }, {
    key: 'handleIOSScheme',
    value: function handleIOSScheme() {
      var _this$options5 = this.options,
        scheme = _this$options5.scheme,
        delay = _this$options5.delay,
        fallback = _this$options5.fallback;
      if (Browser.getIOSVersion() < 9) {
        this.evokeByIFrameDelay(scheme, delay, fallback);
      } else {
        this.evokeByTagADelay(scheme, delay, fallback);
      }
    }
  }, {
    key: 'handleOriginalChrome',
    value: function handleOriginalChrome() {
      var _this = this;
      var _this$options6 = this.options,
        scheme = _this$options6.scheme,
        intent = _this$options6.intent,
        delay = _this$options6.delay,
        fallback = _this$options6.fallback;
      var degradationStrategyFn = function degradationStrategyFn() {
        if (intent && intent.package) {
          _this.evokeByLocationDelay(generateIntent(scheme, intent.package, intent.fallbackUrl), delay, fallback, _this.handleIntent.bind(_this));
        }
      };
      this.evokeByLocationDelay(scheme, delay, fallback, degradationStrategyFn);
    }
    /**
     * @param evokeFn
     * @param delay
     * @param fallback
     * @param degradationStrategy
     */
  }, {
    key: 'evokeAppDelay',
    value: function evokeAppDelay(evokeFn, evokeAppByUrl, delay, fallback, degradationStrategy) {
      var _this2 = this;
      var newDelay = delay || this.config.delay;
      var newFallback = fallback || this.config.fallback;
      this.timer = setTimeout(function () {
        _this2.clearTimer();
        evokeFn();
        _this2.checkIsOpen(evokeAppByUrl, newFallback, degradationStrategy);
      }, newDelay);
    }
  }, {
    key: 'evokeByLocationDelay',
    value: function evokeByLocationDelay(url, delay, fallback, degradationStrategy) {
      this.evokeAppDelay(function () {
        return evokeByLocation(url);
      }, url, delay, fallback, degradationStrategy);
    }
  }, {
    key: 'evokeByTagADelay',
    value: function evokeByTagADelay(url, delay, fallback, degradationStrategy) {
      this.evokeAppDelay(function () {
        return evokeByTagA(url);
      }, url, delay, fallback, degradationStrategy);
    }
  }, {
    key: 'evokeByIFrameDelay',
    value: function evokeByIFrameDelay(url, delay, fallback, degradationStrategy) {
      this.evokeAppDelay(function () {
        return evokeByIFrame(url);
      }, url, delay, fallback, degradationStrategy);
    }
    /**
     * @param fallback
     * @returns
     */
  }, {
    key: 'checkIsOpen',
    value: function checkIsOpen(evokeAppByUrl, fallback, degradationStrategy) {
      this.evokeAppBy.url = evokeAppByUrl;
      return checkCallAppSuccess(degradationStrategy || fallback, this.config.resultJudgmentTime);
    }
  }, {
    key: 'clearTimer',
    value: function clearTimer() {
      if (this.timer) {
        clearTimeout(this.timer);
      }
    }
  }]);
  return CallApp;
}();
export default CallApp;