
const env = process.env.NODE_ENV || 'development';
// const config = require(__dirname + '/../../config/config.json')[env];
const User = require("../../models").users;
const Profile = require("../../models").profiles;
const Project = require("../../models").projects;
const ProjectSubmission = require("../../models").project_submissions;
const ProjectType = require("../../models").project_types;
const Department = require("../../models").departments;
const Institute = require("../../models").institutes;
const {Sequelize,Op} = require("sequelize");
const sequelize  = require("../../config/connection");
const axios = require('axios');
const https = require('https');
const LibraryAccessCode = require("../../models").library_access_codes;
const {randomString} = require("../helpers/randomString")
// At request level
const agent = new https.Agent({
    rejectUnauthorized: false
});

exports.viewResearch = async (req, res) =>{
try {
let projects = []
const COREURL = "https://research.kwarapolyfiles.com/research/view";
const {startDate, endDate, pageNumber, pageSize, projectType, sessionId } = req.query;
const sortColumn = req.query.sortColumn || 'createdAt';
const sortOrder = req.query.sortOrder || 'DESC';


let query = {};
if(projectType)
  query.project_type_id = projectType
if (startDate && endDate) {
  query = {[Sequelize.Op.and]: [
    sequelize.where(sequelize.fn('date', sequelize.col('projects.createdAt')), '>=', startDate),
    sequelize.where(sequelize.fn('date', sequelize.col('projects.createdAt')), '<=', endDate),
  ]}
}
const filter = {};
if (pageNumber)
  filter.offset = parseInt(pageNumber);

  if(sessionId == 1){
    const responseData = await axios.get(`${COREURL}`,{ httpsAgent: agent });
    projects = responseData.data.projects
  }else{
    projects = await Project.findAll({
      limit: pageSize || 10,
      ...filter,
      order: [
        [sortColumn,sortOrder],
      ],
      subQuery:false,
      where:{
        active:true,
        is_completed:true,
          ...query,
      },
      attributes:["id","student_user_id","lecturer_user_id","description","topic","createdAt"],
      
    include:[
      {
        model:ProjectType,
        attributes:["name"],
  
      },
      {
        model:User,
        as:"student",
        attributes:["username"],
        include: [
        { 
          model: Profile,
          include:[
            { 
              model: Department,
              attributes:["id","name"],
              include:[
                { 
                  model: Institute,
                  attributes:["name"]
                }
              ]
            }
          ]
        }
      ],
      },
      {
        model:User,
        as:"lecturer",
        attributes:["username"],
        include:[
          {
            model:Profile,
          }
        ]
      }
    ]
    });
    
  }
return {projects}
} catch (error) {
  console.log(error)
    return res.status(500).send(error.message)
}


};

exports.viewReasearchByDepartment = async (req, res) =>{
  try {

  const { department_id } = req.params;
  let projects = []
  const COREURL = `https://research.kwarapolyfiles.com/research/view/${department_id}`;
  const {startDate, endDate, pageNumber, pageSize, projectType, sessionId } = req.query;
  const sortColumn = req.query.sortColumn || 'createdAt';
  const sortOrder = req.query.sortOrder || 'DESC';
  
  
  let query = {};
  if(projectType)
    query.project_type_id = projectType
  if (startDate && endDate) {
    query = {[Sequelize.Op.and]: [
      sequelize.where(sequelize.fn('date', sequelize.col('projects.createdAt')), '>=', startDate),
      sequelize.where(sequelize.fn('date', sequelize.col('projects.createdAt')), '<=', endDate),
    ]}
  }
  const filter = {};
  if (pageNumber)
    filter.offset = parseInt(pageNumber);
  
    if(sessionId == 1){
      const responseData = await axios.get(`${COREURL}`,{ httpsAgent: agent });
      projects = responseData.data.projects
    }else{
      
    [projects] = await sequelize.query(`SElECT departments.id AS dept_id, projects.id AS id,topic,projects.createdAt AS createdAt,departments.name AS department_name, institutes.name AS institute_name,   
    project_types.name AS project_types_name, firstname, lastname, username FROM projects 
    INNER JOIN project_types ON project_types.id = projects.project_type_id 
    INNER JOIN users ON users.id = projects.student_user_id INNER JOIN profiles ON users.id = profiles.user_id 
    INNER JOIN departments ON departments.id = profiles.department_id INNER JOIN institutes ON institutes.id = departments.institute_id WHERE departments.id = '${department_id}'`);
    }
  return res.status(200).send({projects});
  } catch (error) {
    console.log(error)
      return res.status(500).send(error.message)
  }
  
  
};
exports.searchResearch = async (req, res) => {
try {
  const {startDate,searchTerm,  endDate, pageNumber, pageSize, projectType, sessionId } = req.query;
  if(!searchTerm)
    return res.status(400).send({message:false, message:"Search term is necessary"})
    let projects = []
    const COREURL = new URL(`https://research.kwarapolyfiles.com/research/search?searchTerm=${searchTerm}`); 
  const sortColumn = req.query.sortColumn || 'createdAt';
  const sortOrder = req.query.sortOrder || 'DESC';
  const fullProjects = [];
  let query = {};
  if(projectType)
    query.project_type_id = projectType
  if (startDate && endDate) {
    query = {[Op.and]: [
      sequelize.where(sequelize.fn('date', sequelize.col('dispatch.createdAt')), '>=', startDate),
      sequelize.where(sequelize.fn('date', sequelize.col('dispatch.createdAt')), '<=', endDate),
    ]}
  }
  const filter = {};
  if (pageNumber)
    filter.offset = parseInt(pageNumber);
    if(sessionId == 1){
      const responseData = await axios.get(`${COREURL}`,{ httpsAgent: agent });
      projects = responseData.data.projects
    }else{
      projects = await Project.findAll({
        limit: pageSize || 10,
        ...filter,
        order: [
          [sortColumn,sortOrder],
        ],
        subQuery:false,
        where:{
          topic: {
            [Op.startsWith]: `${searchTerm}`
          },
          active:true,
          is_completed:true,
            ...query,
        },
        attributes:["id","student_user_id","lecturer_user_id","description","topic","createdAt"],
        
      include:[
        {
          model:ProjectType,
          attributes:["name"],
    
        },
        {
          model:User,
          as:"student",
          attributes:["username"],
          include: [
          { 
            model: Profile,
            include:[
              { 
                model: Department,
                attributes:["id","name"],
                include:[
                  { 
                    model: Institute,
                    attributes:["name"]
                  }
                ]
              }
            ]
          }
        ],
        },
        {
          model:User,
          as:"lecturer",
          attributes:["username"],
          include:[
            {
              model:Profile,
            }
          ]
        }
      ]
      });
    }
  
  return res.status(200).send({projects})
  } catch (error) {
    console.log(error)
      return res.status(500).send(error.message)
  }
  
  
};

exports.downloadProject = async (req, res) => {
  try {

     const { project_id } = req.params;
     const COREURL = `https://research.kwarapolyfiles.com/research/download/${project_id}`;
     let folderPath = ""
  const project = await ProjectSubmission.findOne({
    where:{
      project_id,
      document_category_id:7
    },
    raw:true
  });
  if(!project){
    // const responseData = await axios.get(`${COREURL}`,{ httpsAgent: agent });
    // folderPath = `https://research.kwarapolyfiles.com${responseData.data}`
    return res.redirect(`https://research.kwarapolyfiles.com/research/download/${project_id}`)
  }else{
    folderPath = project.document_path;
  }
  // return res.download(folderPath);
  } catch (error) {
    return res.status(500).send({success:false, message:error.message})
  }
};
exports.viewResearchInner = async (req, res) =>{
  try {
  let projects = []
  const {startDate, endDate, pageNumber=1, pageSize, projectType, sessionId } = req.query;
  const COREURL = new URL(`https://research.kwarapolyfiles.com/research/view?pageNumber=${pageNumber}`); 
  const sortColumn = req.query.sortColumn || 'createdAt';
  const sortOrder = req.query.sortOrder || 'DESC';
  
  
  let query = {};
  if(projectType)
    query.project_type_id = projectType
  if (startDate && endDate) {
    query = {[Sequelize.Op.and]: [
      sequelize.where(sequelize.fn('date', sequelize.col('projects.createdAt')), '>=', startDate),
      sequelize.where(sequelize.fn('date', sequelize.col('projects.createdAt')), '<=', endDate),
    ]}
  }
  let page; 
  //? This handles offset error    
  if(req.query.pageNumber === undefined){         page = 0;     } else {         page = +req.query.pageNumber;     }
  const filter = {};
  if (pageNumber)
    filter.offset = page;
  
    if(sessionId == 1){
      const responseData = await axios.get(`${COREURL}`,{ httpsAgent: agent });
      projects = responseData.data.projects
    }else{
      projects = await Project.findAll({
        limit: pageSize || 10,
        ...filter,
        order: [
          [sortColumn,sortOrder],
        ],
        subQuery:false,
        where:{
          active:true,
          is_completed:true,
            ...query,
        },
        attributes:["id","student_user_id","lecturer_user_id","description","topic","createdAt"],
        
      include:[
        {
          model:ProjectType,
          attributes:["name"],
    
        },
        {
          model:User,
          as:"student",
          attributes:["username"],
          include: [
          { 
            model: Profile,
            include:[
              { 
                model: Department,
                attributes:["id","name"],
                include:[
                  { 
                    model: Institute,
                    attributes:["name"]
                  }
                ]
              }
            ]
          }
        ],
        },
        {
          model:User,
          as:"lecturer",
          attributes:["username"],
          include:[
            {
              model:Profile,
            }
          ]
        }
      ]
      });
    }
  return res.status(200).send({projects});
  } catch (error) {
    console.log(error)
      return res.status(500).send(error.message)
  }
  
  
};
exports.generateCafeOTP = async (req, res) => {
  try {
      const { num } = req.params
      for(var i = 0; i < parseInt(num); i++){
          const code = randomString(7)
          const auth_code = `KP-LIB-${code.toLocaleUpperCase()}`;
          await LibraryAccessCode.create({access_code:auth_code, creator: req.user.id, status:false});
      }
      return res.status(201).send({success:true, message:`${num} code has been created!`})
  } catch (error) {
      return res.status(500).send({success:false, message:error.message})
  }
};

exports.deleteCafeOTP = async ( req, res ) => {
  try {
      await LibraryAccessCode.destroy({where:{id:req.params.id}});
      return res.status(201).send({success:true, message:`Code Deleted `})
  } catch (error) {
      return res.status(500).send({success:false, message:error.message})
  }
};
exports.verifyCode = async (req, res) => {
  try {
      const { auth_code } =  req.body
      const user = await LibraryAccessCode.findOne({where:{access_code:auth_code,status:false}})
      if(user){
        return res.status(200).send({success:true, message:"Code available"});
      }
  
      return res.status(200).send({success:false, message:"Invalid Code "});
  } catch (error) {
      return res.status(500).send({success:false,message:error.message})
  }
};