const User = require("../../models").users;
const Profile = require("../../models").profiles;
const Activity = require("../../models").activity_log
const StudentSupervisor = require("../../models").student_supervisors;
const CurrentSession = require("../../models").sessions;
const {randomString} = require("../helpers/randomString");
const readXlsxFile = require('read-excel-file/node');
const fs = require('fs');
const CryptoJS = require("crypto-js");
const secretKey = "4gt71TxD1e4P3433";
var key = CryptoJS.enc.Base64.parse("4gt71TxD1e4P3433");
var iv  = CryptoJS.enc.Base64.parse("4gt71TxD1e4P3433");

exports.studentUpload = async (req,res) =>{
    try {
      const { 
        department_id,
        level_id,
        study_mode_id,
        project_type_id,
    } = req.body;

      let allStaudent = [];
      if (req.file == undefined) {
        return res.redirect(`/student-management?error=${"Please Upload Valid file"}`)
        return res.status(400).send("Please upload an excel file!");
      }
      let path = "./libaries/" + req.file.filename;
      readXlsxFile(path).then( async (students) => {
        students.shift(); // skip header
        for(const student of students){
            let lecturer_id  = "INVALID"
            let session_id = "NONE"
            const username = student[0].toUpperCase();
            const lastname = student[1];
            const firstname = student[2];
            const middlename = student[3];
            const supervisor = student[4]
            const password = CryptoJS.AES.encrypt(firstname, key, {iv: iv}).toString();
        const checkUsername = await User.findOne({where:{username}});
        if(checkUsername)
          continue;
        const lecturer = await User.findOne({where:{username:supervisor}})
        const session = await CurrentSession.findOne({where:{status:true}})
        if(lecturer)
           lecturer_id = JSON.parse(JSON.stringify(lecturer)).id;
        if(session)
          session_id = session.id;
  
        const user = await User.create({
            username,
            slug:randomString(20),
            password,
            role:7
        });
        allStaudent.push(user)
        if(user){
          await Profile.create({
              user_id:user.id,
              department_id,
              level_id,
              study_mode_id,
              firstname,
              lastname,
              middlename,
              role_id:7,
              session_id
          });
          await StudentSupervisor.create({
              project_type_id:1,
              student_user_id:user.id,
              lecturer_user_id:lecturer_id,
          })

        }
        }
        fs.unlink( path, (err => {
          if (err) console.log(err);
          else {
            console.log("\nDeleted file: " + req.file.originalname);
          }
        }));
        return res.redirect(`/student-management?success=true`)
        return res.status(200).send({success:true,data:allStaudent,message:"All students successfully registered successfully"})
      });
    } catch (error) {
      return res.redirect(`/student-management?error=${"File not in correct format: " + req.file.originalname}`)
      res.status(500).send({
        message: "File not in correct format: " + req.file.originalname,
      });
    }
}
exports.singleStudentUplod = async (req, res) => {
  try {
    const {
      username,
      lastname,
      firstname,
      middlename,
      study_mode_id,
      level_id,
      supervisor,
      department_id
      } = req.body;
      let session_id;
      const password = CryptoJS.AES.encrypt(firstname, key, {iv: iv}).toString();
      const session = await CurrentSession.findOne({where:{status:true}})
      if(session){
        session_id  = session.id;
      } 

      const checkUsername = await User.findOne({where:{username}});
      if(checkUsername)
        return res.redirect(`/student-management?error=${"Use already Exist"}`) 
      const user = await User.create({
        username,
        slug:randomString(20),
        password,
        role:7
      });
      if(user){
        await Profile.create({
            user_id:user.id,
            department_id,
            level_id,
            study_mode_id,
            firstname,
            lastname,
            middlename,
            role_id:7,
            session_id
        });
        await StudentSupervisor.create({
            project_type_id:1,
            student_user_id:user.id,
            lecturer_user_id:supervisor,
        })
      }
      return res.redirect(`/student-management?success=true`)

  } catch (error) {
    return res.redirect(`/student-management?error=${"error " + error.message}`) 
  }
};