/**
 * @fileoverview 字符串中不包含http地址
 * @author semious
 */
'use strict';

const unique = require('array-unique');

const strUtil = require('../util/str-util');

// ------------------------------------------------------------------------------
//  Rule Definition
// ------------------------------------------------------------------------------

module.exports = {
  meta: {
    docs: {
      description: '字符串中包含http不安全链接地址',
      category: 'Possible Errors',
      recommended: true
    },
    fixable: null,
    schema: [
      {
        type: 'object',
        properties: {
          exceptions: {
            type: 'array',
            uniqueItems: true
          }
        },
        additionalProperties: false
      }
    ]
  },
  
  create: function (context) {
    
    const httpPattern = /(^|[^a-zA-Z])http:\\?\/\\?\/.+/i;
    const ignoreDomain = unique(['.alipay.net'].concat(context.options[0] ? (context.options[0].exceptions || []) : []));
    
    // ----------------------------------------------------------------------
    //  Helpers
    // ----------------------------------------------------------------------
    /**
     *
     * 是否在忽略的域名里
     *
     * @param {string} str
     * @return {boolean}
     */
    function isIgnoreDomain(str) {
      return ignoreDomain.some(function (domain) {
        return str.indexOf(domain) >= 0;
      });
    }
    
    /**
     * 不含有中文字符
     * @param str
     */
    function notHasChineseChar(str) {
      const pattern = /[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/i;
      return !pattern.test(str);
    }
    
    /**
     * is私有地址
     * @param str
     */
    function isLocalAddress(str) {
      const privateAdd = new RegExp('(localhost|127\\.0\\.0\\.1)','i');
      // console.log(str);
      return privateAdd.test(str);
    }
    
    /**
     * Reports a given variable declaration node.
     *
     * @param {ASTNode} node - A variable declaration node to report.
     * @param {string} url - 含有url的字符串地址
     * @returns {void}
     */
    function report(node, url) {
      
      context.report({
        node,
        message: '字符串中含有http链接:{{url}}',
        data: {
          url
        }
      });
    }
    
    // ----------------------------------------------------------------------
    //  Public
    // ----------------------------------------------------------------------
    
    return {
      
      Literal(node){
        const value = strUtil.getStr(node);
        // console.log(value);
        notHasChineseChar(value) && !isLocalAddress(value)
          && httpPattern.test(value) && !isIgnoreDomain(value)
          && report(node, value);
      }
    };
  }
};
