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'),
  require('./src/api/quiz')
].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.use(App.static('public'))


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);
//router.use(App.static('public'))
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);

const WebSocket = require('ws');

const wss = new WebSocket.Server({
  port: env.WS_PORT,
  perMessageDeflate: {
    zlibDeflateOptions: {
      // See zlib defaults.
      chunkSize: 1024,
      memLevel: 7,
      level: 3
    },
    zlibInflateOptions: {
      chunkSize: 10 * 1024
    },
    // Other options settable:
    clientNoContextTakeover: true, // Defaults to negotiated value.
    serverNoContextTakeover: true, // Defaults to negotiated value.
    serverMaxWindowBits: 10, // Defaults to negotiated value.
    // Below options specified as default values.
    concurrencyLimit: 10, // Limits zlib concurrency for perf.
    threshold: 1024 // Size (in bytes) below which messages
    // should not be compressed.
  }
});
wss.on('connection', function connection(ws) {
  ws.send(JSON.stringify({type: 'connected', data: null}));
});
console.log('WS LISTEN port: '+env.WS_PORT);
global.log = function(type, data){
  try{
    wss.clients.forEach(function each(client) {
        client.send(JSON.stringify({type, data}));
    });
  }catch (e) {

  }
}