/**
 *  通用工具类
 *  ===========================================================================
 */


/**
 * 将文本JSON格式化，第二个参数：是否为压缩模式
 * @param txt
 * @param compress
 * @returns {string}
 */
export const format =(txt,compress/* 是否为压缩模式 */) =>{/* 格式化JSON源码(对象转换为JSON文本) */
  var indentChar = '    ';
  if(/^\s*$/.test(txt)){
    return txt;
  }
  try{var data=eval('('+txt+')');}
  catch(e){
    return txt;
  }
  var draw=[],last=false,This=this,line=compress?'':'\n',nodeCount=0,maxDepth=0;

  var notify=function(name,value,isLast,indent/*缩进*/,formObj){
    nodeCount++;/*节点计数*/
    for (var i=0,tab='';i<indent;i++ )tab+=indentChar;/* 缩进HTML */
    tab=compress?'':tab;/*压缩模式忽略缩进*/
    maxDepth=++indent;/*缩进递增并记录*/
    if(value&&value.constructor==Array){/*处理数组*/
      draw.push(tab+(formObj?('"'+name+'":'):'')+'['+line);/*缩进'[' 然后换行*/
      for (var i=0;i<value.length;i++)
        notify(i,value[i],i==value.length-1,indent,false);
      draw.push(tab+']'+(isLast?line:(','+line)));/*缩进']'换行,若非尾元素则添加逗号*/
    }else   if(value&&typeof value=='object'){/*处理对象*/
      draw.push(tab+(formObj?('"'+name+'":'):'')+'{'+line);/*缩进'{' 然后换行*/
      var len=0,i=0;
      for(var key in value)len++;
      for(var key in value)notify(key,value[key],++i==len,indent,true);
      draw.push(tab+'}'+(isLast?line:(','+line)));/*缩进'}'换行,若非尾元素则添加逗号*/
    }else{
      if(typeof value=='string')value='"'+value+'"';
      draw.push(tab+(formObj?('"'+name+'":'):'')+value+(isLast?'':',')+line);
    };
  };
  var isLast=true,indent=0;
  notify('',data,isLast,indent,false);
  return draw.join('');
};


/**
 * 将xml格式进行格式化
 *  const resultXml = formatXml(originalXml);
 * @param text
 * @returns {string}
 */
export const formatXml = (text) => {
  // 去掉多余的空格
  text = '\n' + text.replace(/(<\w+)(\s.*?>)/g, function ($0, name, props) {
    return name + ' ' + props.replace(/\s+(\w+=)/g, " $1");
  }).replace(/>\s*?</g, ">\n<");

  // 把注释编码
  text = text.replace(/\n/g, '\r').replace(/<!--(.+?)-->/g, function ($0, text) {
    var ret = '<!--' + escape(text) + '-->';
    // alert(ret);
    return ret;
  }).replace(/\r/g, '\n');

  // 调整格式
  var rgx = /\n(<(([^\?]).+?)(?:\s|\s*?>|\s*?(\/)>)(?:.*?(?:(?:(\/)>)|(?:<(\/)\2>)))?)/mg;
  var nodeStack = [];
  var output = text.replace(rgx, function ($0, all, name, isBegin, isCloseFull1, isCloseFull2, isFull1, isFull2) {
    var isClosed = (isCloseFull1 == '/') || (isCloseFull2 == '/' ) || (isFull1 == '/') || (isFull2 == '/');
    //alert([all,isClosed].join('='));
    var prefix = '';
    if (isBegin == '!') {
      prefix = getPrefix(nodeStack.length);
    }
    else {
      if (isBegin != '/') {
        prefix = getPrefix(nodeStack.length);
        if (!isClosed) {
          nodeStack.push(name);
        }
      }
      else {
        nodeStack.pop();
        prefix = getPrefix(nodeStack.length);
      }

    }
    var ret = '\n' + prefix + all;
    return ret;
  });

  var prefixSpace = -1;
  var outputText = output.substring(1);
  // alert(outputText);

  // 把注释还原并解码，调格式
  outputText = outputText.replace(/\n/g, '\r').replace(/(\s*)<!--(.+?)-->/g, function ($0, prefix, text) {
    // alert(['[',prefix,']=',prefix.length].join(''));
    if (prefix.charAt(0) == '\r')
      prefix = prefix.substring(1);
    text = unescape(text).replace(/\r/g, '\n');
    var ret = '\n' + prefix + '<!--' + text.replace(/^\s*/mg, prefix) + '-->';
    // alert(ret);
    return ret;
  });

  return outputText.replace(/\s+$/g, '').replace(/\r/g, '\r\n');
};

function getPrefix(prefixIndex) {
  var span = '    ';
  var output = [];
  for (var i = 0; i < prefixIndex; ++i) {
    output.push(span);
  }
  return output.join('');
}


/**
 * 压缩xml字符串
 */
export const compressXmlStr =(str) =>{
  var prefix, suffix;
  var i = str.indexOf("\r");
  while(i > -1){
    prefix = str.substring(0, i);
    suffix = str.substring(i, str.length);
    suffix = suffix.replace(/(^\s*)|(\s*$)/g, "")
    str = prefix + suffix;
    i = str.indexOf("\r");
  }
  i = str.indexOf("\n");
  while(i > -1){
    prefix = str.substring(0, i);
    suffix = str.substring(i, str.length);
    suffix = suffix.replace(/(^\s*)|(\s*$)/g, "")
    str = prefix + suffix;
    i = str.indexOf("\n");
  }
  return str;
};


/**
 * 判断是否是jSON格式
 * @param str
 * @returns {boolean}
 */
export const isJson = (str) => {
  if (typeof str == 'string') {
    try {
      var obj=JSON.parse(str);
      if(typeof obj == 'object' && obj ){return true;
      }else{return false;}
    } catch(e) {return false;}
  }
};
