var env = process.env;

const APP_HOST = env.APP_HOST || "127.0.0.1";
const APP_PORT = env.APP_PORT || 4000;
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)
};

router.get('ivasic', async function(req, res) {
  res.end(print('lalka'));
});


router.all('/', function(req, res) {
  res.end(print(JSON.stringify(data)));
});


var path = require('path');

var cache = {};
var bCore = require( "@babel/core" );
var jsxServe = function(dir) {
  return function (req, res, next) {
    if (req.url in cache) {
      return res.end(cache[req.url])
    }
    /*if (req.url.substr(-8) === '.jsx.map') {
      debugger
    }*/
    if (req.url.substr(-4) === '.jsx') {
      fs.readFile(path.join(dir, req.url), function(err, data){
        debugger
        if( err ){
          next();
        }else{
          bCore.transform(
            data+'',
            {
              "plugins": [
                [ "@babel/plugin-transform-react-jsx", {
                  "pragma": "D.h", // default pragma is React.createElement
                  "pragmaFrag": "D.f", // default is React.Fragment
                  "throwIfNamespace": false // defaults to true
                } ]
              ],
              sourceMaps: 'both',
              sourceFileName: req.url
            }, function( c, d, e ){
              if(c){
                res.end(c.message+'\n'+c.stack)
              }else{
                debugger
                cache[ req.url + '.map' ] = JSON.stringify( d.map );
                res.set( 'SourceMap', req.url + '.map' );
                res.end( d.code )
              }
            } );
        }
      });

    } else {
      next();
    }
  }
};

app.use(jsxServe('public'));
app.use(App.static('public'))
app.use('/', function(req, res) {
  res.end(print(JSON.stringify(data)));
});

app.listen(APP_PORT);

console.log(`LISTEN port :`+APP_PORT);
