'use strict';

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var isNum = _interopDefault(require('./isNum'));
var isStr = _interopDefault(require('./isStr'));
var unique = _interopDefault(require('./unique'));
var randomNum = _interopDefault(require('./randomNum'));
var consts = require('./consts');

var charNb = consts.ID_CHAR_SET.number;
var charLower = consts.ID_CHAR_SET.letter;
var charUpper = charLower.toUpperCase();
var charSpecial = consts.ID_CHAR_SET.special;

/**
 * 随机生成一个字符串ID
 * @param {*} length
 * @param {*} charSet
 * [*] 表示 0-9a-zA-Z和特殊字符组合，不可组合
 * [s] 表示随机特殊字符，可组合
 * 0-9 表示0-9的随机值，可组合
 * a-z 表示a-z的随机值，可组合
 * A-Z 表示A-Z的随机值，可组合
 * @returns {string}
 *
 * randomId();              // => '4LOC8VP7ATDP' (随机)
 * randomId(18);            // => 'CCG7F097IBFX472RYR' (随机)
 * randomId(10, '0-9[s]');  // => '0#0_49' (随机)
 * randomId('a-z_-');       // => 'm_u_l--axfgh' (随机)
 * randomId('a-zA-Z');      // => 'EwOObdxHzrMn' (随机)
 * randomId('[*]');         // => 'uET6nQ_*6%P~' (随机)
 */
function randomId(length, charSet) {
  if (isStr(length)) charSet = length;
  if (!isNum(length)) length = 12;
  var chars = '';

  if (!charSet || !isStr(charSet)) {
    chars = charNb + charUpper;
  } else if (charSet === '[*]') {
    chars = charNb + charLower + charUpper + charSpecial;
  } else if (charSet.match(/0-9|a-z|A-Z|\[s\]/)) {
    if (/0-9/.test(charSet)) chars += charNb;
    if (/a-z/.test(charSet)) chars += charLower;
    if (/A-Z/.test(charSet)) chars += charUpper;
    if (/\[s\]/.test(charSet)) chars += charSpecial;
    chars += unique(charSet.replace(/0-9|a-z|A-Z|\[s\]/g, ''));
  } else {
    chars = charSet;
  }

  var str = '';
  var i = -1;

  while (++i < length) {
    str += chars[randomNum(chars.length)];
  }

  return str;
}

module.exports = randomId;
