
function sqlEscape(str) {
  return (str+'').replace(/[\0\x08\x09\x1a\n\r"'\\\%]/g, function (char) {
    switch (char) {
      case "\0":
        return "\\0";
      case "\x08":
        return "\\b";
      case "\x09":
        return "\\t";
      case "\x1a":
        return "\\z";
      case "\n":
        return "\\n";
      case "\r":
        return "\\r";
      case "\"":
      case "'":
      case "\\":
      case "%":
        return "\\"+char; // prepends a backslash to backslash, percent,
                          // and double/single quotes
      default:
        return char;
    }
  });
}
const indexKey = {
    connections: 'cid',
    tags: 'id'//'iID'
  },
  yamlEscape = function(a) {
    return typeof a === 'number'? a : '\''+(a+'').replace(/'/,'\'\'')+'\''
  };
const formatters = {
  json: function(data) {
    return JSON.stringify(data, null, 2);
  },
  csv: toCSV,
  sql: function(data) {
    if(data.length){
      const item = data[0], header = [];
      for(let key in item){
        header.push(key);
      }
      const rows = data.map(item=>header.map(key=>item[key]));
      return [ 'INSERT INTO `' + store.get( 'exportTableName' ) + '` (' + header.map( sqlEscape ).map( a => '`' + a + '`' ).join( ', ' ) + ') VALUES' ].concat(
        rows.map( row => '(' + row.map( sqlEscape ).map( a => '\'' + a + '\'' ).join( ', ' ) + ')' ).join( ',\n' )
      ).join( '\n' ) + ';';
    }else{
      return ';'
    }
  },
  yaml: function(data, exportData) {
    const index = indexKey[exportData]
    return data
      .map(item=>
        [exportData.substr(0,exportData.length-1)+item[index]+':'].concat(
          Object.keys(item)
            .filter(key=>key !== index)
            .map(key=>'  '+key+': '+ yamlEscape(item[key]))

        ).join('\n')
      ).join('\n')
  }
};



const exportLogic = function(exportEl) {
  store.sub(['exportData', 'exportFormat'], function(exportData, exportFormat) {
    var arr = [];
    var fullData = dP[exportData];
    for(var k in fullData){
      arr.push(fullData[k]);
    }
    exportEl.value = exportFormat in formatters ? formatters[exportFormat](arr, exportData): 'Create formatter '+exportFormat;
  });
  return exportEl;
};