const db = require("../models");
const API = require('../helper/API_Response');
const db_helper = require("../helper/db_helper");
const helper = require("../helper/helper");
const { MeetingChats, Flashcard, StudyMaterial, QuestionDiscussion, User, References, Books } = require("../models");

exports.add = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  res.status(200).send(API._200(await db_helper.addData('Meetings', input)));
};
exports.byId = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  res.status(200).send(API._200(await db_helper.byId('Meetings', input.id)));
};
exports.delete = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const result = await db.sequelize.query("delete from meetings where id= :id", { replacements: { id: input.id } }).then((res) => {
    return Array.from(new Set(res));
  })
  res.status(200).send(API._200(await result));
};
exports.get_message = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const all = await MeetingChats.findAll({
    where: {
      status: 0,
      meeting_id: input.meeting_id,
    },
    order: [
      ['createdAt', 'DESC'],
      ['id', 'ASC'],
    ],
    include: [{
      model: User,
      attributes: ['id', 'email', 'name', 'aliasname', 'avatar_url']
    }],
    limit: [input.limitRecord, 100]
  });
  res.status(200).send(API._200(await all));
};
exports.get_single_message = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const all = await MeetingChats.findAll({
    where: {
      status: 0,
      meeting_id: input.meeting_id,
    },
    order: [
      ['createdAt', 'DESC'],
      ['id', 'ASC'],
    ],
    include: [{
      model: User,
      attributes: ['id', 'email', 'name', 'aliasname', 'avatar_url']
    }],
    limit: [10]
  });
  res.status(200).send(API._200(await all));
};
exports.save_message = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  res.status(200).send(API._200(await db_helper.addData('MeetingChats', input)));
};
exports.get_know_report = async (req, res) => {
  debugger
  const data = await helper.decryptRequest(req.body.data);
  var ass_ids = [];
  const know_assess = await db.sequelize.query("SELECT ka.id,ka.knowass_name,case when RowNumber is not null then true  else false end ViewSummeryicon from knowledge_asses as ka inner join cohorts as c on find_in_set(ka.id,c.knowassessments) left join (SELECT count(ass_id) RowNumber ,ass_id,cohort_id FROM know_ass_ques_ans where active=0 and cohort_id= :cohort_id  and user_id= :user_id group by ass_id,cohort_id)  ret on ret.ass_id=ka.id and ret.cohort_id=c.id where ka.certi_id= :cource_id and find_in_set(" + data.user_id + ",c.userslist) and ka.status=0 and c.id= :cohort_id  group by ka.id, ka.knowass_name,ret.RowNumber", { replacements: { user_id: data.user_id, cohort_id: data.cohort_id, cource_id: data.cource_id } })
    .then((data) => {
      ass_ids = Array.from(new Set(data[0]));
    });
  var d = [];
  if (ass_ids.length > 0) {
    var c_date_data = await db_helper.selectByWhere('KaComplete', { user_id: data.user_id, cohort_id: data.cohort_id }, ['createdAt', 'ka_id']);
    var schedule_data = await db_helper.selectByWhere('CohortSchedule', { type: "KA", cohort_id: data.cohort_id }, ['due_date', 'overdue_date', 'type_id']);

    for (let i = 0; i < ass_ids.length; i++) {

      const knowAssQues = await db.sequelize.query(`SELECT ans,correct from know_ass_ques_ans WHERE cohort_id=${data.cohort_id} AND user_id=${data.user_id} AND active=1 AND ass_id=${ass_ids[i].id}`).then(data => Array.from(new Set(data[0])));
      const knowAss = await db.sequelize.query(`SELECT id from know_ass_ques WHERE FIND_IN_SET(${ass_ids[i].id}, ass_id) and status=0`).then(data => Array.from(new Set(data[0])));

      let schedule = schedule_data.filter(x => x.type_id == ass_ids[i].id)
      let c_date = "";
      if (c_date_data.length > 0) {
        let c_date_array = c_date_data.filter(x => x.ka_id == ass_ids[i].id)
        if (c_date_array.length > 0) {
          c_date = c_date_array[0].createdAt;
        } else {
          c_date = "";
        }
      } else {
        c_date = "";
      }
      let correct = [];
      correct = await knowAssQues.filter(res => res.correct == 1);
      let wrong = [];
      wrong = await knowAssQues.filter(res => res.correct == 0);
      let dknow = [];
      dknow = await knowAssQues.filter(res => res.correct == "2");
      var r = await {
        ass_id: ass_ids[i].id,
        knowass_name: ass_ids[i].knowass_name,
        user_id: data.user_id,
        currect: correct.length,
        dknow: dknow.length,
        panding: knowAss.length - (correct.length + wrong.length + dknow.length),
        wrong: wrong.length,
        total: wrong.length + correct.length + (knowAss.length - (correct.length + wrong.length)),
        c_date,
        schedule,
        ViewSummeryicon: ass_ids[i].ViewSummeryicon
      }
      let ab = await r;
      await d.push(ab);

    }
  } else {
    res.status(200).send(API._200(await d));
  }
  res.status(200).send(API._200(await d));
};

exports.filter_knowledge_question = async (req, res) => {
  const data = await helper.decryptRequest(req.body.data);

  var q = "";
  if (data.RowNumber > 0) {
    q = "Select kaq.*,(CASE WHEN kaqa.ans IS NULL then false ELSE true END) as answered,kaqa.ans as user_ans from (SELECT *, @cur:= IF(KAQ_id=@id, @cur+1, 1) AS RowNumber, @id := KAQ_id FROM know_ass_ques_ans t CROSS JOIN(SELECT @id:=(SELECT MIN(KAQ_id) FROM know_ass_ques_ans where active=0 and cohort_id=" + data.cohort_id + " and ass_id=" + data.ass_id + " and user_id=" + data.user_id + "), @cur:=0) AS init where active=0 and cohort_id=" + data.cohort_id + " and ass_id=" + data.ass_id + " and user_id=" + data.user_id + " ORDER BY t.KAQ_id) as kaqa RIGHT JOIN know_ass_ques as kaq ON kaqa.KAQ_id=kaq.id WHERE FIND_IN_SET(" + data.ass_id + ",kaq.ass_id) and kaq.status=0 AND kaqa.RowNumber=" + data.RowNumber;
  } else {
    q = "Select * from know_ass_ques as kaq WHERE FIND_IN_SET(" + data.ass_id + ",kaq.ass_id) and kaq.status=0";
  }
  for (const [key, value] of Object.entries(data)) {
    if (key != "ass_id" && key != "user_id" && key != "cohort_id" && key != "method_id" && key != "material_type" && key != "method_type" && key != "RowNumber") {
      q += " and kaq." + key + "=" + value;
    }
  }

  const knowAssQues = await db.sequelize.query(q)
    .then(function (data) {
      return Array.from(new Set(data[0]));
    })
  let knowAssQuesAns = []
  if (data.RowNumber <= 0) {
    knowAssQuesAns = await db.sequelize.query("Select (CASE WHEN kaqa.ans IS NULL then false ELSE true END) as answered,kaqa.ans as user_ans,KAQ_id from (select * from know_ass_ques_ans where cohort_id=" + data.cohort_id + " and active=1 and user_id=" + data.user_id + " and ass_id=" + data.ass_id + ") as kaqa")
      .then(function (data) {
        return Array.from(new Set(data[0]));
      })
  }
  for (let i = 0; i < knowAssQues.length; i++) {
    if (data.RowNumber <= 0) {
      let answers = knowAssQuesAns.filter(x => x.KAQ_id == knowAssQues[i].id)
      if (answers.length > 0) {
        knowAssQues[i].answered = answers[0].answered;
        knowAssQues[i].user_ans = answers[0].user_ans;
      } else {
        knowAssQues[i].answered = 0;
        knowAssQues[i].user_ans = null;
      }
    }
  }
  if (!knowAssQues) {
    res.status(404).send(API._404({ message: "No data found" }));
  }
  res.status(200).send(API._200(await knowAssQues.sort((a, b) => a.id - b.id)));
};

exports.knowledge_result_pagination = async (req, res) => {
  const data = await helper.decryptRequest(req.body.data);
  var offset = (data.pageNumber - 1) * data.pageSize;
  var limit = data.pageSize;
  var q = "";
  if (data.RowNumber > 0) {
    q = "Select kaq.*,(CASE WHEN kaqa.ans IS NULL then false ELSE true END) as answered,kaqa.ans as user_ans from (SELECT *, @cur:= IF(KAQ_id=@id, @cur+1, 1) AS RowNumber, @id := KAQ_id FROM know_ass_ques_ans t CROSS JOIN(SELECT @id:=(SELECT MIN(KAQ_id) FROM know_ass_ques_ans where active=0 and cohort_id=" + data.cohort_id + " and ass_id=" + data.ass_id + " and user_id=" + data.user_id + "), @cur:=0) AS init where active=0 and cohort_id=" + data.cohort_id + " and ass_id=" + data.ass_id + " and user_id=" + data.user_id + " ORDER BY t.KAQ_id) as kaqa RIGHT JOIN know_ass_ques as kaq ON kaqa.KAQ_id=kaq.id WHERE FIND_IN_SET(" + data.ass_id + ",kaq.ass_id) and kaq.status=0 AND kaqa.RowNumber=" + data.RowNumber + "  LIMIT " + limit + " OFFSET " + offset;
  } else {
    q = "Select * from know_ass_ques as kaq WHERE FIND_IN_SET(" + data.ass_id + ",kaq.ass_id) and kaq.status=0  LIMIT " + limit + " OFFSET " + offset;
  }
  for (const [key, value] of Object.entries(data)) {
    if (key != "ass_id" && key != "user_id" && key != "cohort_id" && key != "method_id" && key != "material_type" && key != "method_type" && key != "RowNumber" && key != 'pageSize' && key != 'pageNumber') {
      q += " and kaq." + key + "=" + value;
    }
  }
  const cohort_data = await db_helper.query("select videos,mindmaps,flashcard_access,video_access,mindmap_access,summary_access,reference_access from cohorts where id=" + data.cohort_id);
  const knowAssQues = await sequelize.query(q)
    .then(function (data) {
      return Array.from(new Set(data[0]));
    })
  let knowAssQuesAns = []
  if (data.RowNumber <= 0) {
    knowAssQuesAns = await sequelize.query("Select (CASE WHEN kaqa.ans IS NULL then false ELSE true END) as answered,kaqa.ans as user_ans,KAQ_id from (select * from know_ass_ques_ans where cohort_id=" + data.cohort_id + " and active=1 and user_id=" + data.user_id + " and ass_id=" + data.ass_id + ") as kaqa")
      .then(function (data) {
        return Array.from(new Set(data[0]));
      })
  }
  for (let i = 0; i < knowAssQues.length; i++) {
    if (data.RowNumber <= 0) {
      let answers = knowAssQuesAns.filter(x => x.KAQ_id == knowAssQues[i].id)
      if (answers.length > 0) {
        knowAssQues[i].answered = answers[0].answered;
        knowAssQues[i].user_ans = answers[0].user_ans;
      } else {
        knowAssQues[i].answered = 0;
        knowAssQues[i].user_ans = null;
      }
    }
    const fls = await Flashcard.findAll({
      where: {
        topic_id: knowAssQues[i].topic_id,
        status: 0
      },
      attributes: ['id', 'term', 'definition']
    });
    var study = [];
    study = await StudyMaterial.findAll({
      where: {
        topic_id: knowAssQues[i].topic_id,
        status: 0
      },
      attributes: ['id', 'title', 'content']
    });
    let vquery = "";

    vquery = "select id,video_title,video_thumbnil,duration,type,topic_list,video_link from videos where status=0  and find_in_set(" + knowAssQues[i].topic_id + ",topic_id) order by sr_number";
    var video = await db_helper.query(vquery);
    const dissc = await QuestionDiscussion.findAll({
      where: {
        test_id: knowAssQues[i].ass_id,
        test_type: 'KA',
        q_id: knowAssQues[i].id,
        status: 0
      },
      include: [{
        model: User,
        attributes: ['id', 'name', 'email', 'avatar_url']
      }]
    });
    var refers = [];
    refers = await References.findAll({
      where: {
        topic_id: knowAssQues[i].topic_id,
        status: 0
      },
      include: [{
        model: Books,
        attributes: ['id', 'book_title', 'book_img']
      }]
    });
    var mind = await db_helper.query("select id,thumbnail_link,name from mind_maps where status=0  and find_in_set(" + knowAssQues[i].topic_id + ",topic_id) order by sr_number");
    knowAssQues[i].Flashcards = fls;
    knowAssQues[i].StudyMaterials = study;
    knowAssQues[i].Video = video[0];
    knowAssQues[i].Discussion = dissc;
    knowAssQues[i].References = refers;
    knowAssQues[i].MindMaps = mind[0];

    knowAssQues[i].MindMapsAccess = cohort_data[0][0].mindmap_access;
    knowAssQues[i].ReferencesAccess = cohort_data[0][0].reference_access;
    knowAssQues[i].VideoAccess = cohort_data[0][0].video_access;
    knowAssQues[i].StudyMaterialsAccess = cohort_data[0][0].summary_access;
    knowAssQues[i].FlashcardAccess = cohort_data[0][0].flashcard_access;
  }

  if (!knowAssQues) {
    res.status(404).send(API._404({ message: "No data found" }));
  }
  res.status(200).send(API._200(await knowAssQues.sort((a, b) => a.id - b.id)));
};


exports.delete_meeting_chats = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  let message = input.meeting_name + " has been completed ";
  const notifications = await db_helper.query("update notifications set noti_type='complete_meeting', message='" + message + "' where test_type='meeting' and test_id=" + input.meeting_id);
  const result = await db.sequelize.query("delete from meeting_chats where meeting_id= :id", { replacements: { id: input.meeting_id } }).then((res) => {
    return Array.from(new Set(res));
  })
  res.status(200).send(API._200(await result));
};
exports.update = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  res.status(200).send(API._200(await db_helper.update('Meetings', input)));
};