/* eslint-disable vars-on-top */
/* eslint-disable no-var */
const express = require('express');

const router = express.Router();

const userApi = require('../api/users');
const editApi = require('../api/editable');
const clearApi = require('../api/auto-clear');

async function isAuthenticated(req, res, next) {
  if (req.user && req.isAuthenticated()) {
    var editable = await editApi.isEditable(req.session.passport.user.jwt);
    var autoClear = await clearApi.autoClear(req.session.passport.user.jwt);
    res.locals.editable = editable ? editable.attributes.Active : false;
    res.locals.autoClear = autoClear ? autoClear.attributes : null;
    res.locals.role = req.session.passport.user.role ? req.session.passport.user.role.name : null;
    if(res.locals.role !='Admin'){
      req.session.companySelected = req.session.passport.user.company;
      req.session.divisionSelected = req.session.passport.user.division;
    }
    return next();
  }

  return res.redirect('/login');
}

router.post('/change', isAuthenticated, async (req, res) => {
  var user = req.body.user;
  var state = req.body.state;
  var editor = req.body.editor;
  if(user && state){
    var changeUser = await userApi.setState(req.session.passport.user.jwt,req.body.user,req.body.state == 'Active'?true:false);
    if(!changeUser){
      return res.redirect('/users?s=err');
    }
  }
  if(user && editor){
    var setEditor = await userApi.setEditor(req.session.passport.user.jwt,req.body.user,editor);
    if(!setEditor){
      return res.redirect('/users?s=err');
    }
  }
  return res.redirect('/users');
});

router.post('/delete', isAuthenticated, async (req, res) => {
    var user = req.body.user;
    if(user){
        var deleteUser = await userApi.deleteUser(req.session.passport.user.jwt,req.body.user);
        if(!deleteUser){
            return res.redirect('/users?s=err');
        }
    }
    return res.redirect('/users');
  });

module.exports = router;
