/**
 * 运行环境处理
 */
window.Promise = require('promise');

export default class Env {
  constructor() {
    this.isWeiXin = false;
    this.isWeiXinDev = false;
    this.isIe = false;
    this.isChrome = false;
    this.isSafari = false;
    this.isFirefox = false;
    this.isOpera = false;
    this.isIpad = false;
    this.isIpod = false;
    this.isIphone = false;
    this.isAndroid = false;
    this.isWindowPhone = false;
    this.isMobile = false;
    this.isIos = false;
    this.width = 0;
    this.height = 0;
    this.initPlant();
    this.initFunc();
  }

  initPlant() {
    /**
     * 当前访问场景初始化
     */
    const agent = window.navigator.userAgent.toLowerCase();
    this.isIpad = agent.match(/ipad/i) === 'ipad';
    this.isIpod = agent.match(/ipod/i) === 'ipod';
    this.isIphone = agent.match(/iphone os/i) === 'iphone os';
    this.isAndroid = agent.match(/android/i) === 'android';
    this.isWindowPhone = agent.match(/windows phone/i) === 'windows phone';
    this.isSymbian = agent.match(/symbianos/i) === 'symbianos';
    this.isWeiXin = agent.match(/MicroMessenger/i) === 'micromessenger';
    this.isIe = agent.match(/msie/i) === 'msie';
    this.isFirefox = agent.match(/firefox/i) === 'firefox';
    this.isChrome = agent.match(/chrome/i) === 'chrome';
    this.isSafari = agent.match(/safari/i) === 'safari';
    this.isOpera = agent.match(/opera/i) === 'opera';
    if (this.isIpad || this.isIpod || this.isIphone) this.isIos = true;
    if (this.isIpad || this.isIpod || this.isIphone || this.isAndroid || this.isWindowPhone || this.isSymbian) {
      this.isMobile = true;
    } else {
      this.isPc = true;
    }
  }

  initFunc() {
    /**
     * 当前环境基本接口初始化
     */
    window.Promise.prototype.end = function(callback) {
      let error = null;
      window.Promise._87 = function(self, err) {
        error = err;
      };
      window.Promise.resolve()
        .then(() => {
          return this;
        })
        .catch(err => {
          callback(err);
          throw err;
        })
        .then(result => {
          callback(error || result);
          return result;
        });
      return this;
    };
  }
}
