const csv = require('csv-parser'),
      fs = require('fs'),
      path = require('path');

const readCSV = async function(scope) {
  const {fileName, types, keys, index} = scope,
    postProcess = scope.postProcess || (a => a);

  const trash = Symbol('Trash')
  const hash = {};
  return await new Promise(function(resolve, reject) {
    let id = 1;
    const inc = ()=>id++;

    fs.createReadStream(fileName)
      .pipe(csv({
        mapHeaders: ({header}) => keys[header] || trash,
        mapValues: ({header, value}) => header in types ? types[header](value) : null
      }))
      .on('data', (obj) => {
        postProcess(obj, inc);
        hash[obj[index]] = obj;
      })
      .on('end', () => {
        resolve(hash);
        console.log('CSV parsed: '+ fileName)
      });
  });
};
const base = process.env.KUS_DATA_DIR || './data';

const connections = JSON.parse(fs.readFileSync(path.join(base,'connections.json'))+'');
const tags = JSON.parse(fs.readFileSync(path.join(base,'tags.json'))+'');

data = {tags, connections};
(async()=>{
  data.components = await readCSV({
    fileName: path.join(base,'components.csv'),
    keys: {
      'номер карточки': 'id',
      'ингредиент': 'name'
    },
    types: {
      id: Number,
      name: String
    },
    postProcess: (a, inc) => a.iID = inc(),
    index: 'iID'
  });

  data.products = await readCSV({
    fileName: path.join(base,'products.csv'),
    keys: {
      '': 'id',
      'название': 'title',
      'описание': 'description',
      'категория': 'cat',
      'подкатегория': 'subcat',
      'подподкатегория': 'subsubcat',
      'участвует в тесте': 'use'
    },
    types: {
      id: Number,
      title: String,
      description: String,
      cat: String,
      subcat: String,
      subsubcat: String,
      use: a=>Boolean(Number(a))
    },
    index: 'id'
  });
  data.after && data.after(data);
})();


const keys = {
  'номер карточки': 'id',
  'ингредиент': 'name'
};
const mapper = {
  id: Number,
  name: String
};

module.exports = data;