const db = require("../models");
const API = require('../helper/API_Response');
const db_helper = require("../helper/db_helper");
const helper = require("../helper/helper");
const { Flashcard, StudyMaterial, QuestionDiscussion, User, References, Books, KnowAssQuesAns,
  KnowAssQues, Domain, Subdomain, Topic, KnowledgeAsses, Certificate } = require("../models");

exports.filterQues = 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 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 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;
      }
    }
    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.knowAssQueAnsAdd = async (req, res) => {
  const data = await helper.decryptRequest(req.body.data);
  var knowAss;
  knowAss = await KnowAssQuesAns.findAll({
    where: {
      KAQ_id: data.KAQ_id,
      user_id: data.user_id,
      ass_id: data.ass_id,
      cohort_id: data.cohort_id,
      active: 1,
      status: 0
    }
  });
  if (knowAss.length === 0) {
    res.status(200).send(API._200(await db_helper.addData('KnowAssQuesAns', data)));
  } else {
    if (data.ans == 0 || data.ans > 0) knowAss[0].ans = data.ans;
    res.status(200).send(API._200(await knowAss[0].save()));
  }
};
exports.knowAssReport = async (req, res) => {
  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", { 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 validation, COUNT(*) as count
                    FROM (
                        SELECT kaq.d_id, (
                        CASE 
                            WHEN kaqa.ans IS NULL THEN 'pending' 
                            WHEN (CASE WHEN kaq.answer = 'FALSE' THEN '1' ELSE '0' END) = kaqa.ans THEN 'true' 
                            ELSE 'false' 
                        END
                        ) as validation 
                        FROM know_ass_ques AS kaq 
                        LEFT JOIN (
                        SELECT kaq_id, ans 
                        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}
                        ) AS kaqa ON kaq.id=kaqa.KAQ_id 
                        WHERE FIND_IN_SET(${ass_ids[i].id}, kaq.ass_id) AND kaq.status=0
                    ) AS a 
                    LEFT JOIN domains ON domains.id=a.d_id 
                    WHERE domains.certi_id=${data.cource_id} AND domains.status=0 
                    GROUP BY validation
                    `).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 currect = [];
      currect = await knowAssQues.filter(res => res.validation == "true");
      let wrong = [];
      wrong = await knowAssQues.filter(res => res.validation == "false");
      let pending = [];
      pending = await knowAssQues.filter(res => res.validation == "pending");
      var r = await {
        ass_id: ass_ids[i].id,
        knowass_name: ass_ids[i].knowass_name,
        user_id: data.user_id,
        currect: currect.length > 0 ? currect[0].count : 0,
        panding: pending.length > 0 ? pending[0].count : 0,
        wrong: wrong.length > 0 ? wrong[0].count : 0,
        total: (currect.length > 0 ? currect[0].count : 0) + (pending.length > 0 ? pending[0].count : 0) + (wrong.length > 0 ? wrong[0].count : 0),
        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.knowAssDomainReport = async (req, res) => {
  const data = await helper.decryptRequest(req.body.data);
  var d_ids = [];
  const domain_list = await db.sequelize.query("SELECT id,domin_name from domains where certi_id= :cource_id and status=0", { replacements: { cource_id: data.cource_id } })
    .then((data) => {
      d_ids = Array.from(new Set(data[0]));
    });
  var d = [];

  if (d_ids.length == 0) {
    res.status(404).send(API._404({ message: 'No data found' }));
  }
  const knowAss = await db.sequelize.query(`SELECT id from know_ass_ques WHERE FIND_IN_SET(${data.ass_id}, ass_id) and status=0`).then(data => Array.from(new Set(data[0])));
  for (let i = 0; i < d_ids.length; i++) {

    let knowAssQues = "";
    if (data.RowNumber > 0) {
      knowAssQues = await db.sequelize.query("Select @cur:= IF(kaqa.KAQ_id=@id, @cur+1, 1) AS RowNumber, kaqa.ans,kaqa.correct from know_ass_ques_ans as kaqa where user_id=" + data.user_id + " and cohort_id=" + data.cohort_id + " and ass_id=" + data.ass_id + " and active=0 and d_id=" + d_ids[i].id + " and @cur:= IF(kaqa.KAQ_id=@id, @cur+1, 1)=" + data.RowNumber)
        .then(function (data) {
          return Array.from(new Set(data[0]));
        });;
    } else {
      knowAssQues = await db.sequelize.query("SELECT ans,correct FROM know_ass_ques_ans WHERE user_id=" + data.user_id + " AND active=1 AND ass_id=" + data.ass_id + " AND cohort_id=" + data.cohort_id + " AND d_id=" + d_ids[i].id)
        .then(function (data) {
          return Array.from(new Set(data[0]));
        })
    }
    let currect = [];
    currect = await knowAssQues.filter(res => res.correct == 1);
    let wrong = [];
    wrong = await knowAssQues.filter(res => res.correct == 0);
    let dontknow = [];
    dontknow = await knowAssQues.filter(res => res.ans == 2);

    let r = {
      d_id: d_ids[i].id,
      domain_name: d_ids[i].domin_name,
      user_id: data.user_id,
      currect: currect.length,
      panding: knowAss.length - (currect.length + wrong.length + dontknow.length),
      wrong: wrong.length,
      dontknow: dontknow.length,
      total: currect.length + wrong.length + dontknow.length + (knowAss.length - (currect.length + wrong.length + dontknow.length))
    }

    let ab = await r;
    d.push(ab);
    if (i == d_ids.length - 1) {
      d = d.sort(function (a, b) {
        return a.d_id - b.d_id;
      });
    }
  }
  res.status(200).send(API._200(await d));
};
exports.getUserReportKnowAssQuesAnsByUser = async (req, res) => {
  const data = await helper.decryptRequest(req.body.data);
  var ass_ids = [];
  const know_assess = await db.sequelize.query("SELECT ka.id,ka.knowass_name from knowledge_asses as ka inner join cohorts as c on find_in_set(ka.id,c.knowassessments) where find_in_set(" + data.user_id + ",c.userslist) and ka.status=0 group by ka.id")
    .then((data) => {
      ass_ids = Array.from(new Set(data[0]));
    });

  const dt = new Promise((resolve, reject) => {
    var d = [];
    if (ass_ids.length == 0) {
      res.status(404).send(API._404({ message: 'No data found' }));
    }
    ass_ids.forEach(async (ass_id, i) => {

      const knowAssQues = await db.sequelize.query("select * from (SELECT kaq.*,(CASE WHEN kaqa.ans IS NULL then 'pending' WHEN kaq.answer=kaqa.ans THEN 'true' ELSE 'false' END) as validation FROM know_ass_ques as kaq LEFT JOIN (SELECT * from know_ass_ques_ans where user_id=" + data.user_id + " and active=1 and ass_id=" + ass_id.id + ") as kaqa ON kaq.id=kaqa.KAQ_id WHERE FIND_IN_SET(" + ass_id.id + ",kaq.ass_id) and kaq.status=0) as a LEFT join domains on domains.id=a.d_id where domains.status=0")
        .then(function (data) {
          return Array.from(new Set(data[0]));
        });

      let currect = [];
      currect = await knowAssQues.filter(res => res.validation == "true");
      let wrong = [];
      wrong = await knowAssQues.filter(res => res.validation == "false");
      let pending = [];
      pending = await knowAssQues.filter(res => res.validation == "pending");

      var r = await {
        ass_id: ass_id.id,
        knowass_name: ass_id.knowass_name,
        user_id: data.user_id,
        currect: currect.length,
        panding: pending.length,
        wrong: wrong.length,
        total: currect.length + wrong.length + pending.length
      }

      if (!knowAssQues) {
        res.status(404).send(API._404({ message: 'No data found' }));
      };
      let ab = await r;
      d.push(ab);

      if (i == ass_ids.length - 1) {
        resolve(d);
      }
    })
  });
  res.status(200).send(API._200(await dt));
};

exports.getKnowAssQuesForId = async (req, res) => {
  const knowAssQuesId = await helper.decryptUri(req.params.id)
  var result = new Promise(async (resolve, reject) => {
    const dd = await KnowAssQues.findAll({
      where: {
        id: knowAssQuesId,
        status: 0
      },
      include: [{
        model: Domain,
        attributes: ['id', 'domin_name']
      }, {
        model: Subdomain,
        attributes: ['id', 'subdomain_name']
      }, {
        model: Topic,
        attributes: ['id', 'topic_name']
      }]
    }).then((res) => {
      if (res.length == 0) { resolve([]) };

      res.forEach(async (responce, j) => {

        const ass_ids = await responce.get('ass_id');
        var arr = [];
        let datas = await ass_ids.forEach(async (element, i) => {
          let data = await KnowledgeAsses.findAll({
            attributes: ['id', 'knowass_name'],
            where: {
              status: 0,
              id: element
            }
          }).then(resp => {
            if (resp[0]) {
              arr.push(resp[0]);
              if ((i + 1) == ass_ids.length) {
                responce = responce.toJSON()
                responce.knowledge_asses = arr.map((a) => a.toJSON())
                if ((j + 1) == res.length) {
                  resolve(responce);
                }
              }
            } else {
              reject(res.status(404).send(API._404({ message: `KnowlageAsses ass_id was not found` })));
            }
          });
        });
      });

    })

  }).catch((ex) => {
    res.status(404).send(API._404({ message: `KnowlageAsses ass_id was not found` }));
  })
  res.status(200).send(API._200(await result));
};

exports.knowAssQuesAdd = async (req, res) => {
  const data = await helper.decryptRequest(req.body.data);
  const knowAssQues = await KnowAssQues.create(data);
  res.status(200).send(API._200(await knowAssQues));
};
exports.knowAssQuesAll = async (req, res) => {
  let knowAssQues = new Promise(async (resolve, reject) => {
    KnowAssQues.findAll({
      where: {
        status: 0
      },
      include: [{
        model: Certificate,
        attributes: ['id', 'certificate_name']
      },
      {
        model: Domain,
        attributes: ['id', 'domin_name']
      }, {
        model: Subdomain,
        attributes: ['id', 'subdomain_name']
      }, {
        model: Topic,
        attributes: ['id', 'topic_name']
      }
      ]
    }).then((res) => {
      if (res.length == 0) { resolve([]) };
      res.forEach(async (responce, j) => {

        const ass_ids = await responce.get('ass_id');
        var arr = [];
        let datas = await ass_ids.forEach(async (element, i) => {
          let data = await KnowledgeAsses.findAll({
            attributes: ['id', 'knowass_name'],
            where: {
              status: 0,
              id: element
            }
          }).then(resp => {
            if (resp[0]) {
              arr.push(resp[0]);
              if ((i + 1) == ass_ids.length) {
                res[j] = res[j].toJSON()
                res[j].knowledge_asses = arr.map((a) => a.toJSON())
                if ((j + 1) == res.length) {
                  resolve(res);
                }
              }
            } else {
              if (!res) reject(res.status(404).send(API._404({ message: 'KnowledgeAsses not found ' })));
            }
          });
        });
      });
      if (!res) reject(res.status(404).send(API._404({ message: 'KnowledgeAsses not found ' })));
    })
  }).catch((ex) => {
    res.status(404).send(API._404({ message: 'KnowledgeAsses not found ' }))
  })
  res.status(200).send(API._200(await knowAssQues));
};

exports.updateKnowAssQues = async (req, res) => {
  const id = await helper.decryptUri(req.params.id)
  const input = await helper.decryptRequest(req.body.data);
  const knowAssQues = await KnowAssQues.findByPk(id)
  if (!knowAssQues) {
    res.status(404).send(API._404({ message: `Know Ass question with id: ${id} was not found` }));
  }
  if (input.ass_id) knowAssQues.ass_id = input.ass_id
  if (input.question) knowAssQues.question = input.question
  if (input.d_id) knowAssQues.d_id = input.d_id
  if (input.sd_id) knowAssQues.sd_id = input.sd_id
  if (input.topic_id) knowAssQues.topic_id = input.topic_id
  if (input.subtopic_id) knowAssQues.subtopic_id = input.subtopic_id
  if (input.answer) knowAssQues.answer = input.answer
  if (input.ref_link) knowAssQues.ref_link = input.ref_link
  if (input.youtube_link) knowAssQues.youtube_link = input.youtube_link
  if (input.bookpage_no) knowAssQues.bookpage_no = input.bookpage_no
  if (input.blog_url) knowAssQues.blog_url = input.blog_url
  if (input.description) knowAssQues.description = input.description
  if (input.point) knowAssQues.point = input.point
  if (input.certi_id) knowAssQues.certi_id = input.certi_id
  if (input.status) knowAssQues.status = input.status
  res.status(200).send(API._200(await knowAssQues.save()));
};

exports.deleteKnowAssQues = async (req, res) => {
  const knowAssQuesId = await helper.decryptUri(req.params.id)
  const knowAssQues = await KnowAssQues.findByPk(knowAssQuesId).then(async res1 => {
    res1.set("status", 1);
    return await res1.save();
  })
  if (!knowAssQues) {
    res.status(404).send(API._404({ message: `KnowAssQues with id: ${knowAssQuesId} was not found` }));
  }
  res.status(200).send(API._200(await knowAssQues));
};