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 transformJSX = function(code, fileName, cb) {
  bCore.transform(
    code,
    {
      "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: fileName
    }, function( c, d, e ){
      if(c){
        cb(c);

      }else{
        cb(false, d);
      }
    } );
};

var transformServe = 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(-45 === '.scss') {

    }else if (req.url.substr(-4) === '.jsx') {
      fs.readFile(path.join(dir, req.url), function(err, data){
        if( err ){
          next();
        }else{
          transformJSX(data+'', req.url, function(err, result) {
            if(err){
              res.end(err.message+'\n'+err.stack)
            }else{
              cache[ req.url + '.map' ] = JSON.stringify( result.map );
              res.set( 'SourceMap', req.url + '.map' );
              res.end( result.code )
            }
          })
        }
      });

    } else {
      next();
    }
  }
};

app.use(transformServe('public'));
app.use(App.static('public'))
var lives = [];
app.use('/', function(req, res, next) {
  if(req.originalUrl === '/'){
    res.end( print( JSON.stringify( data ) ) );
  }else if(req.originalUrl === '/[live]'){
    lives.push(res);
  }
});



const util = require('util');
const readFile = util.promisify(fs.readFile);
const transformJSXPromised = util.promisify(transformJSX);

let debounce = {};
let shouldUpdate = false;
var doUpdate = async function(){

  var files = [];
  for( let filename in debounce ){
    try{
      var code = await readFile( filename ) + '';
      var result = await transformJSXPromised( code, path.relative( './public', filename ) );
      files.push( { file: '/'+path.relative( './public', filename ).replace(/\\/g, '/'), content: result.code } );
    }catch( e ){

      console.log( 'Error in ' + e );
    }
    delete debounce[filename];

  }
  var live, liveUpdate = JSON.stringify(files);
  while((live = lives.pop()))
    live.end(liveUpdate);
  shouldUpdate = false;
};
let debounceUpdate = function(filename){
  if(filename.indexOf('_tmp_')===-1 && filename.indexOf('_old__')===-1){
    debounce[ filename ] = true;
    if(!shouldUpdate){
      shouldUpdate = true;
      setTimeout(doUpdate, 300);
    }
  }
};
var watch = require('recursive-watch');
watch('./public', function(filename){
  if(filename.indexOf('_tmp_')>-1)
    return;

  debounceUpdate(filename);
});




app.listen(APP_PORT);

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