var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var layouts = require('express-ejs-layouts');
var sqlite3 = require('sqlite3');

const fs = require('fs');
const session = require('express-session');

// Connect to (or create) database
var db = new sqlite3.Database('./database.db', (err) => {
  if (err) {
    console.log(err);
    exit(1);
  }
});

// Create tables
try {
  let sql = fs.readFileSync('tlc.sql', 'utf8');
  db.exec(sql);
} catch (err) {
  console.log(err);
  exit(1);
}

global.db = db;

var aboutRouter = require('./routes/about');
var catalogRouter = require('./routes/catalog');
var contactRouter = require('./routes/contact');
var customerRouter = require('./routes/customer');
var helpRouter = require('./routes/help');
var indexRouter = require('./routes/index');
var orderdetailRouter = require('./routes/orderdetail');
var privacyRouter = require('./routes/privacy');
var productRouter = require('./routes/product');
var promotionRouter = require('./routes/promotion');
var reportRouter = require('./routes/report');
var saleorderRouter = require('./routes/saleorder');
var searchRouter = require('./routes/search');

var app = express();

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

app.use(session({secret: 'TennisBallsCompanyAppSecret'}));
app.use(function(req, res, next) {
  res.locals.session = req.session;
  next();
});

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/about', aboutRouter);
app.use('/catalog', catalogRouter);
app.use('/contact', contactRouter);
app.use('/customer', customerRouter);
app.use('/help', helpRouter);
app.use('/orderdetail', orderdetailRouter);
app.use('/privacy', privacyRouter);
app.use('/product', productRouter);
app.use('/promotion', promotionRouter);
app.use('/report', reportRouter);
app.use('/saleorder', saleorderRouter);
app.use('/search', searchRouter);

// 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');
});

module.exports = app;
