const express = require('express');
const morgan = require('morgan');
const exphbs = require('express-handlebars');
const path = require('path');
const flash = require('connect-flash');
const session = require('express-session');
const MySQLStore = require('express-mysql-session');
const passport = require('passport');
const multer = require('multer');
const { v4: uuidv4 } = require('uuid');

const fs = require('fs');

const Rollbar = require("rollbar");

var rollbar = new Rollbar({
  accessToken: 'ce7c7a535a6041c59033de55e96cd691',
  captureUncaught: true,
  captureUnhandledRejections: true
});

// record a generic message and send it to Rollbar
//rollbar.log("Hello world!");

const  {database} = require('./keys');
const bodyParser = require('body-parser');


// ***Aqui en esta session va las inicializaciones ***//
const app = express();

require('./lib/passport');

try {
//*** */  
//*** Settings o configuraciones ***// 
    //* configuracion del motor de plantilla handlebars */
    app.set('views',path.join(__dirname,'views'));
    app.set('port',process.env.PORT || 8086);
    app.engine('.hbs',exphbs({
        defaultLayout: 'main',
        layoutsDir: path.join(app.get('views'), 'layouts'),
        partialsDir: path.join(app.get('views'), 'partials'),
        extname: '.hbs',
        helpers: require('./lib/handlebars')
    }));
    app.set('view engine', '.hbs');
    
      //*  fin de configuracion del motor de plantillas **//
    
      var allowCrossDomain = function(req, res, next){
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
        res.header('Access-Control-Allow-Headers', 'Content-Type');
        next();
      }
    
    
    //*** Middlewares (funciones que se ejecutan cada vez que exista una peticion al servidor)***//
    
    app.use(require('express-status-monitor')());
    app.use(session ( {
      secret: 'cofasa',
      resave: false,
      saveUninitialized: false,
      store: new MySQLStore(database)
    }));
    app.use(flash());
    app.use(morgan('dev'));
    // este modulo me permite aceptar los formularios que envies los usuarios desde los clientes
    app.use(bodyParser.json({
      limit: '20mb'
    }));
    
    app.use(bodyParser.urlencoded({
      limit: '20mb',
      parameterLimit: 100000,
      extended: true 
    }));
    
     const storage = multer.diskStorage({
         destination: path.join(__dirname, 'public/uploads'),
         filename: (req, file, cb) => {
          cb(null, uuidv4() + path.extname(file.originalname));
         }
     });
     app.use(multer({storage}).single('image'));
    
    //**** */
    
    
    app.use(express.urlencoded({extended: false}));
    app.use(express.json());
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(allowCrossDomain);
    
    
    
    //*** variables globales de la aplicacion ****//
    app.use((req,res,next) => {
      app.locals.mensajeOk = req.flash('mensajeOk');
      app.locals.message = req.flash('message');
      app.locals.user = req.user;
      next();  
    });
    
    //*** aqui van todas las rutas o las url 
    
    app.use(require('./routes/index'));
    app.use(require('./routes/authentication'));
    app.use('/links', require('./routes/links'));
    
    
    
    //*** public ***//
    app.use(express.static(path.join(__dirname,'public')));
    
    app.use(rollbar.errorHandler());
    
    //*** inicio del servidor ***//
    
    
    app.listen(app.get('port'), () => {
        console.log('el servidor esta en el puerto', app.get('port'));
    });
    

//***** */

} catch (err) {
  manejo_de_errorPrincipal (err)
}


function  manejo_de_errorPrincipal (err)  {
  rollbar.error(err.stack + 'modulo Principal');
  console.log(err.stack);
}

//***************fin**************** *///
