require('dotenv').config()
var createError  = require('http-errors');
var express      = require('express');
var path         = require('path');
var cookieParser = require('cookie-parser');
var logger       = require('morgan');
var session      = require('express-session')
var MySQLStore   = require('express-mysql-session')(session);
var fs           = require('fs')
var mysql2       = require('mysql2/promise');

var indexRouter  = require('./routes/index');
var adminRouter  = require('./routes/admin');
var pageNotFound = require('./routes/404');

var app = express();
const date = new Date()
const logs = fs.createWriteStream(__dirname + "/logs/" + `${date.getDate()}-${date.toLocaleString('default', { month: 'short' })}-${date.getFullYear()}.log`, { flags: "a" })

const moment = require("moment");

app.use((req, res, next) => {
  res.locals.moment = moment;
  next();
});

// session
var options = {
  host: process.env.host,
  user: process.env.user,
  database: process.env.sessiondb,
  password: process.env.password
}

var storeOptions = {
  createDatabaseTable: true,
  schema: {
    tableName: 'sessions',
    columnNames: {
      session_id: 'session_id',
      expires: 'expires',
      data: 'data'
    }
  }
}

var connection = mysql2.createPool(options);
var sessionStore = new MySQLStore(storeOptions, connection);

app.use(session({
  secret: 'bPRYQYxQTn9VSnCQC6hCD7oUplnFXS2W5ohU2CPaDbASy2wlbGr2738mgIle76Cv',
  saveUninitialized: false,
  cookie: { maxAge: 1000 * 60 * 60 * 24, secure: false },
  resave: false,
  store: sessionStore,
}))

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");

app.use(logger('combined', {
  stream: logs,
  skip: (req, res) => res.statusCode < 404
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

app.use('/', indexRouter);
app.use('/admin', adminRouter);
app.use(pageNotFound);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

app.listen(3000);

module.exports = app;
