var env = process.env;

const APP_HOST = env.APP_HOST || "127.0.0.1";
const APP_PORT = env.APP_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 fs = require( 'fs' );

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/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('Open /api for details');
});
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
  res.header("Access-Control-Allow-Headers", "*");
  res.header("Access-Control-Allow-Origin","*");
  next();
});
app.use(router);
app.use(App.static('public'))
app.use(function(req, res, next) {
  req.end('Nope');
})
try{
  app.listen( APP_PORT );
}catch(e){
  console.error(e.message);
}
console.log(`LISTEN port :`+APP_PORT);
