var express = require('express');
var router = express.Router();
var CPage = require('../lib/page.controller');
var CMenu = require('../lib/menu.controller');
var CSensor = require('../lib/sensors.controller');
var CChart = require('../lib/chart.controller');
var CConfig = require('../lib/config.controller');
var CUser = require('../lib/user.controller');


function restrict(req, res, next) {
  if (req.session.user) {
    next();
  } else {
    req.session.error = 'Access denied!';
    res.redirect('/manager/login');
  }
}

/******************************************************************************/
/*************************          GET         *******************************/
/******************************************************************************/

router.get('/', function(req, res){
  res.redirect('/manager/home');
});

/* GET manager login page. */
router.get('/login', function(req, res, next) {
  res.render('manager/managerLogin', {url:"/manager/auth"});
});

/* GET manager logout page. */
router.get('/logout', function(req, res, next) {
  // destroy the user's session to log them out
  // will be re-created next request
  req.session.destroy(function(){
    res.redirect('/');
  });
});

/* GET manager home page. */
router.get('/:content', restrict, function(req, res){
  var content = req.params.content;
  
  if(content == 'home'){
    CSensor.initHomeManager(function(result){
      res.render('manager/managerHome', result);
    });  
  }else if(content == 'menu'){
    CMenu.getListMenu(function(result){
      res.render('manager/managerMenu', result);
    });
  }else if(content == 'charts'){
    CChart.getListCharts(function(result){
      CSensor.getSensorType(function(resu){
        res.render('manager/managerCharts', {Charts: result, Sensors: resu});
      });
    });
  }else if(content == 'pages'){
    CPage.getListPages(function(result){
      CChart.getListCharts(function(charts){
        res.render('manager/managerPages', {Pages: result, Charts: charts});
      });
    });
  }else if(content == 'config'){
    CConfig.loadJson(function(err, json){
      if(!err)
        res.render('manager/managerGlobalConfig', { config: json});
      else
        res.render('error',{ message: 'Error reading/loading global config', error: {} });
    });
  }else{
    // not found
  }
  
});

/* GET Menu/page/chart by Id */
router.get('/:item/:id', restrict, function(req,res){
  var item = req.params.item;
  var id = req.params.id;
  
  if(item == 'menu'){
    CMenu.getMenuById(id ,function(result){
      res.send(JSON.stringify( result ));
    });    
  }else if(item == 'page'){
    CPage.getPageById(id ,function(result){
      res.send(JSON.stringify( result ));
    });    
  }else if(item == 'chart'){
    CChart.getChartById(id ,function(result){
      res.send(JSON.stringify( result ));
    });  
  }
});

/******************************************************************************/
/************************          POST         *******************************/
/******************************************************************************/

/* POST authentication data. */
router.post('/auth', function(req, res, next) {
  
  CUser.authenticateUser(req.body.username, req.body.password, function(result){
    if(result == 1){
      req.session.regenerate(function(){
        // Store the user's name in the session
        req.session.user = req.body.username;
        res.redirect('/manager/home');
      });
    }else{
      res.redirect('login');
    }
  });
});

/* POST add sensor/location/menu/page/chart, traditional version */
router.post('/add/:type', restrict, function(req, res, next){
  if(req.params.type == 'sensor'){
    var TipoSensor = req.body.TipoSensor;
    var LocationSensor = req.body.LocationSensor;
    
    CSensor.insertSensor(TipoSensor, LocationSensor, function(result){
      res.redirect('/manager/');
    });

  }else if(req.params.type == 'address'){
    var name = req.body.nameLocation;
    
    CSensor.insertLocation(name, function(result){
      res.redirect('/manager/');
    });

  }else if(req.params.type == 'menu'){
    var itemPadre = req.body.itemPadre;
    var nameItem = req.body.nameItem;
    var urlItem = req.body.urlItem;
    
    CMenu.insertItemMenu(itemPadre, nameItem, urlItem, function(result){
      res.redirect('/manager/menu');
    });
    
  }else if(req.params.type == 'page'){
    var ptitulo = req.body.titulo;
    var purl = req.body.url;
    var pcontenido = req.body.contenido;
    var ptipo = req.body.pagetype_filter;
    var ptemplate = "";
    if(ptipo == 1){
      ptemplate = "contentPage"; // default template
    }else{
      ptemplate = req.body.template;
    }
    
    CPage.insertPage(ptitulo, purl, pcontenido, ptipo, ptemplate, function(result){
      res.redirect('/manager/pages');
    });
  }else if(req.params.type == 'chart'){
    var cname = req.body.nombre;
    var ctipo = req.body.tipoGrafico;
    var cformato = req.body.formatoGrafico;
    var cbtns = null;
    if(req.body.hasbtns)
      cbtns = 1;
    else
      cbtns = 0;

    CChart.insertChart(cname, ctipo, cformato, cbtns, function(result){
      res.redirect('/manager/charts');
    });
  
  }else if(req.params.type == 'charttopage'){
    var pid = req.body.pid;
    var cid = req.body.cid;
    CChart.insertChartToPage(pid, cid, function(result){
      res.send("chart added");
    });
    
  }
  
  
});

/* POST active sensor, Ajax version */
router.post('/sensor/:id/:state', restrict, function(req, res, next){
  var id = req.params.id;
  var state = req.params.state;

  CSensor.updateSensor(id, state, function(result){
    res.send("sensor actualizado");
  });

});

/* POST edit menu/page/chart, traditional version */
router.post('/edit/:type',  restrict, function(req, res){
  var type = req.params.type;
  
  if(type == 'page'){
    var pid = req.body.idEditPage;
    var ptitulo = req.body.titulo;
    var purl = req.body.url;
    var pcontenido = req.body.contenido;
    
    CPage.updatePage(pid, ptitulo, purl, pcontenido, function(result){
      res.redirect('/manager/pages');
    });  
  }else if(type == 'menu'){
    var mid = req.body.idEditMenu;
    var itemPadre = req.body.itemPadre;
    var nameItem = req.body.nameItem;
    var urlItem = req.body.urlItem;
    
    CMenu.updateMenu(mid, itemPadre, nameItem, urlItem, function(result){
      console.log("update menu: "+result);
      res.redirect('/manager/menu');
    });
  
  
  }else if(type == 'chart'){
    var cid = req.body.idEditChart;
    var cname = req.body.nombre;
    var ctipo = req.body.tipoGrafico;
    var cformato = req.body.formatoGrafico;
    var cbtns = null;
    if(req.body.hasbtns)
      cbtns = 1;
    else
      cbtns = 0;
    console.log(cid+" "+cname+" "+ctipo+" "+cformato+" "+cbtns);
    CChart.updateChart(cid, cname, ctipo, cformato, cbtns, function(result){
      console.log("update chart: "+result);
      res.redirect('/manager/charts');
    });
  }
  
  
});

/* POST delete menu/page/chartfrompage/chart item */
router.post('/delete/:type', restrict, function(req, res){
  
  var type = req.params.type;
  
  if(type == 'menu'){
    var mid = req.body.id;
    CMenu.deleteItemMenuById(mid, function(result){
      res.send('item deleted');
    });
    
  }else if(type == 'page'){
    var pid = req.body.id;
    CPage.deletePageById(pid, function(result){
      res.send('page deleted');
    });
  
  }else if(type == 'chartfrompage'){
    var pid = req.body.pid;
    var cid = req.body.cid;
    CChart.deleteChartFromPage(pid, cid, function(result){
      res.send('chart deleted');
    });
  }else if(type == 'chart'){
    var cid = req.body.id;
    CChart.deleteChartById(cid, function(result){
      res.send('chart deleted');
    });
    
  }
  
});

/* POST save global config */
router.post('/save/config', restrict, function(req, res){
  
  var ninitial = parseInt(req.body.nInicial);
  var nrealtime = parseInt(req.body.nRealtime);
  var nsec = parseInt(req.body.nSeg);
  var json = {};
  
  if(ninitial == "" || ninitial == 0) ninitial = 100;
  if(nrealtime == "" || nrealtime == 0) nrealtime = 50;
  if(nsec == "" || nsec == 0) nsec = 10;
  
  json['global'] = {
    "nInitial": ninitial,
    "nRealtime": nrealtime,
    "nSec": nsec
  };
  
  CConfig.writeJson(json, function(err, result){
    res.redirect('/manager/config');
  });
  
  
});

module.exports = router;
