var UA_MATCH_RULES = [{
  matchRule: 'AppleWebKit\\/([0-9\\.]+).* Version\\/([0-9\\._]+) Mobile\\/([0-9\\._A-Z]+) Safari\\/([0-9\\._]+)$',
  iosScheme: 'https',
  andScheme: ''
}, {
  matchRule: 'HeyTapBrowser',
  iosScheme: '',
  andScheme: ''
}, {
  matchRule: 'HuaweiBrowser',
  iosScheme: '',
  andScheme: ''
}, {
  matchRule: 'Kwai',
  iosScheme: 'kwai',
  andScheme: ''
}, {
  matchRule: 'MQQBrowser',
  iosScheme: 'mttbrowser',
  andScheme: ''
}, {
  matchRule: 'MicroMessenger',
  iosScheme: '',
  andScheme: ''
}, {
  matchRule: 'MiuiBrowser',
  iosScheme: '',
  andScheme: ''
}, {
  matchRule: 'Mozilla\\/([0-9\\.]+).* AppleWebKit\\/([0-9\\.]+).* CriOS\\/([0-9\\._]+) Mobile\\/([0-9\\._A-Z\\._a-z]+) Safari\\/([0-9\\._]+)$',
  iosScheme: 'googlechrome',
  andScheme: ''
}, {
  matchRule: 'Mozilla\\/([0-9\\.]+).* AppleWebKit\\/([0-9\\.]+).* Version\\/([0-9\\._]+) Mobile Safari\\/([0-9\\._]+)$',
  iosScheme: 'googlechrome',
  andScheme: ''
}, {
  matchRule: 'NewsArticle',
  iosScheme: 'snssdk141',
  andScheme: ''
}, {
  matchRule: 'UCBrowser',
  iosScheme: 'ucbrowser',
  andScheme: ''
}, {
  matchRule: 'VideoArticle',
  iosScheme: 'snssdk32',
  andScheme: ''
}, {
  matchRule: 'VivoBrowser',
  iosScheme: '',
  andScheme: ''
}, {
  matchRule: 'ZhongAnWebView',
  iosScheme: 'zaapp',
  andScheme: ''
}, {
  matchRule: 'aweme',
  iosScheme: 'snssdk1128',
  andScheme: ''
}, {
  matchRule: 'aweme_lite',
  iosScheme: 'snssdk2329',
  andScheme: ''
}, {
  matchRule: 'com.xs.fm',
  iosScheme: 'novelfm3040',
  andScheme: ''
}, {
  matchRule: 'netdisk',
  iosScheme: '',
  andScheme: ''
}, {
  matchRule: 'qqnews',
  iosScheme: 'qqnews',
  andScheme: ''
}];

/**
 * 通过配置规则检测 UA 和获得回跳 scheme
 */
export function getBackScheme(mockUa, logger) {
  var ua = mockUa || window.navigator.userAgent || '';
  // 获取规则
  var uaMatchedRule = UA_MATCH_RULES;
  var matchedRule;
  var matched = null;
  for (var i = 0; i < uaMatchedRule.length; i++) {
    var rule = uaMatchedRule[i];
    matched = ua.match(rule.matchRule);
    if (matched) {
      matchedRule = rule;
      break;
    }
  }
  if (!matchedRule) {
    logBackScheme(logger, ua, '');
    return;
  }
  if (isAndroid(ua)) {
    logBackScheme(logger, ua, matchedRule.andScheme);
    return matchedRule.andScheme;
  }
  if (isIOS(ua)) {
    logBackScheme(logger, ua, matchedRule.iosScheme);
    return matchedRule.iosScheme;
  }
}
function logBackScheme(logger, userAgent, scheme) {
  if (logger) {
    logger.logInfo({
      title: 'a3753.b101271.c377460'
    }, {
      eventMessage: scheme
    });
  }
}

/**
 * 当前运行环境是否 Android
 */
function isAndroid(mockUA) {
  var ua = (mockUA || navigator.userAgent).toLowerCase();
  return /android|adr|linux/.test(ua);
}

/**
 * 当前运行环境是否 IOS
 */
function isIOS(mockUA) {
  var ua = (mockUA || navigator.userAgent).toLowerCase();
  return /iphone|ipad|ipod|ios|macintosh/.test(ua);
}