var express = require('express');
var router = express.Router();
var session;

//Database
var postgres = require("./../db-connect/db-connect");

// GoogleOauth2.0
passport = require('passport'),
auth = require('../public/login/auth');
auth(passport);
router.use(passport.initialize());

cookieParser = require('cookie-parser'),
cookieSession = require('cookie-session');

router.use(cookieSession({
  name: 'session',
  keys: ['smartshopper']
}));

router.use(cookieParser());

router.get('/', (req, res) => {
  // var userToken = req.session.passport.user.token;
  console.log("USER TOKEN PASSPORT: ", userToken);
    // if (userToken) {
    //   res.redirect('/dash');
    // } else {
      res.redirect('/auth/google');
    // }
});
router.get('/auth/google', passport.authenticate('google', {
    scope: ['https://www.googleapis.com/auth/userinfo.profile']
}));
router.get('/auth/google/callback',
  passport.authenticate('google', {failureRedirect:'/'}),
  (req, res) => {
    req.session.passport.user.token = req.user.token;
    res.redirect('/dash');
  }
);

router.get('/logout', (req, res) => {
  req.logout();
  req.session = null;
  res.redirect('/');
});

router.get('/dash', function(req, res, next) {
  console.log("Session: ", req.session.passport.user.token);
  console.log("User ID: " + req.session.passport.user.profile.id);
  if (req.session.passport.user.token) {
    res.render('index');
  } else {
    res.redirect('/auth/google');
  }
});

//GET Own shoppinglists as JSON

router.get("/myshoppinglists", async function(req, res, next) {
  try {
    //Get user id: req.session.passport.user.profile.id
    res.status(200).send(await postgres.getShoppinglistsAdmin(req.session.passport.user.profile.id));
  }

  catch(err) {
    res.status(400).send(await err);
  }
      
});

//GET Shared shoppinglists as JSON

router.get("/sharedshoppinglists", async function(req, res, next) {
  try {
    //Get user id: req.session.passport.user.profile.id
    res.status(200).send(await postgres.getShoppinglistsShared(req.session.passport.user.profile.id));
  }

  catch(err) {
    res.status(400).send(await err);
  }
      
});

//POST new shoppinglist

router.post("/shoppinglist", async function(req, res, next) {
  try {
    res.status(200).send(await postgres.newShoppinglist(req.body.name, req.body.description, req.session.passport.user.profile.id));
  }

  catch(err) {
    res.status(400).send(await err);
  }
});

module.exports = router;
