var parsed =  require('dotenv').config();
const fs = require( 'fs' );
if(parsed.error){
  parsed = require('dotenv').parse(fs.readFileSync('./.env.example', 'utf-8'));
  if(!parsed.error){
    for (const k in parsed) {
      process.env[k] = parsed[k].split('|')[0]
    }
  }
}


var env = process.env;

const APP_HOST = env.APP_HOST || "127.0.0.1";
const APP_PORT = env.KUS_GENERATOR_PORT || 4001;
const DB_PATH = env.DB_PATH || "./db/users.json";

const data = require("./db.js");
const App = require('express');
const Router  = require('node-async-router');

const app = App(),
      router = Router();





const tpls = {
  index: fs.readFileSync('./index.html')+''
};
const print = function(data) {
  return tpls.index.replace('$DATA$', data)
};

const api = [require('./src/api/generateRandom'),require('./src/api/log'), require('./src/api/crud')].reduce((store, el)=>{
  return Object.assign(store, el)
}, {});
const {api2html, api2routes} = require('./src/apiMappers.js');
/*
const api = {
  '/api/generate/random': {
    summary: 'Generate random quiz',
    options:{
      seed: {required: false, description: 'initialize random state. Make response determined', type: String},
      photo: {required: false, description: 'question with photo', type: Boolean},
      type: {required: false, description: '1 - products, 2 - standards', type: Number}
    },
    fn: async function() {

    }
  }
};*/
api2routes(api, router);
router.get('/api', async function(req, res) {
  res.end(fs.readFileSync('./public/API.html', 'utf-8').replace('$API$', api2html(api)));
});


router.all('/', function(req, res) {
  res.end(print(JSON.stringify(data)));
});
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
  res.header("Access-Control-Allow-Headers", "*, Accept, Content-Type, Content-Length, Accept-Encoding, CUSTOM-ALLOWED-HEADER");
  res.header("Access-Control-Allow-Origin","*");
  next();
});
app.use(router);
app.use(App.static('public'))
app.use(function(req, res, next) {

  res.end('Nope');
});
try{
  app.listen( APP_PORT );
}catch(e){
  console.error(e.message);
}
console.log(`LISTEN port :`+APP_PORT);
