var express = require('express'),
  app = express(),
  bodyParser = require('body-parser');
var methodOverride = require('method-override');
var Category = require('./models/category');
var passport = require('passport'),
  localStrategy = require('passport-local'),
  passportLocalMongoose = require('passport-local-mongoose');
User = require('./models/user');
var flash = require('express-flash');
require('dotenv').config();

var mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
  console.log('database connected');
});

app.use(express.static('public'));

app.use(
  express.json({
    limit: '50mb',
    type: ['application/json', 'text/plain'],
  })
);
app.use(bodyParser.urlencoded({ limit: '50mb', extended: false }));
app.set('view engine', 'ejs');

app.use(methodOverride('_method'));

app.use(function (req, res, next) {
  Category.find({})
    .populate('Sub_items')
    .exec(function (err, cats) {
      res.locals.menu = cats;
      next();
    });
});

app.use(flash());

//session
app.use(
  require('express-session')({
    secret: 'secret',
    resave: false,
    saveUninitialized: false,
  })
);

/***passport config */
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.urlencoded({ extended: true }));
passport.use(new localStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

app.use(function (req, res, next) {
  res.locals.currentUser = req.user;
  next();
});

/*********** ROUTES */
app.get('/', function (req, res) {
  if (req.user) {
    if (req.user.role == 'admin')
      if (!req.headers.referer.includes("admin")) {
        req.flash('info', "No Client Found");
        return res.redirect("/login");
      }
      else return res.redirect("/admin");
  }
  res.redirect('/home');
});

var productRoutes = require('./routes/product');
var cartRoutes = require('./routes/cart');
var categoryRoutes = require('./routes/category');
var checkoutRoutes = require('./routes/checkout');
var useRoutes = require('./routes/user');
var ordeRoutes = require('./routes/order');
var adminRoutes = require('./routes/admin');
var legalRoutes = require('./routes/legal');
var about = require('./routes/about');

app.use(productRoutes);
app.use(cartRoutes);
app.use(categoryRoutes);
app.use(checkoutRoutes);
app.use(useRoutes);
app.use('/order', isLoggedIn, ordeRoutes);
app.use(adminRoutes);
app.use('/legal', legalRoutes);
app.use('/about', about);

function isLoggedIn(req, res, next) {
  if (req.isAuthenticated()) return next();
  else {
    res.redirect('/login');
  }
}


var port = process.env.PORT || 4030;
app.listen(port, process.env.IP || '0.0.0.0', function () {
  console.log('started at: ' + port);
});
