const db = require("../models");
const API = require('../helper/API_Response');
const db_helper = require("../helper/db_helper");
const helper = require("../helper/helper");
const { Acronyms, PracticeAns, Subdomain, Books, Flashcard, StudyMaterial, QuestionNotes, References, Topic, PracticeAppque, Certificate, Domain, Cource, Practiceque, Practicetest } = require("../models");

exports.addpracticetestans = async (req, res) => {
  const data = await helper.decryptRequest(req.body.data);
  var practiceAns;
  practiceAns = await PracticeAns.findAll({
    where: {
      PTQ_id: data.PTQ_id,
      user_id: data.user_id,
      test_id: data.test_id,
      cohort_id: data.cohort_id,
      active: 1,
      status: 0
    }
  });

  if (practiceAns.length === 0) {
    const practiceTestAns = await PracticeAns.create(data);
    res.status(200).send(API._200(await practiceTestAns));

  } else {
    if (data.ans == 0 || data.ans > 0) practiceAns[0].ans = data.ans;
    if (data.ans_time) practiceAns[0].ans_time = data.ans_time;
    res.status(200).send(API._200(await practiceAns[0].save()));
  }
};
exports.getdomainreportpracticetestans = 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 status=0 and certi_id= :course_id", { replacements: { course_id: data.course_id } })
    .then((data) => {
      d_ids = Array.from(new Set(data[0]));
    });
  const dt = new Promise(async (resolve, reject) => {
    var d = [];

    if (d_ids.length == 0) {
      reject(res.status(404).send(API._404({ message: 'No Data Found' })));
    };

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

      const practiceQues = await db.sequelize.query("SELECT (CASE WHEN ptqa.ans IS NULL then 'pending' WHEN ptq.answer=ptqa.ans THEN 'true' ELSE 'false' END) as validation from practiceques as ptq left join practice_ans as ptqa on ptqa.PTQ_id=ptq.id and ptqa.cohort_id= :cohort_id and ptqa.user_id= :user_id and ptqa.active=1 and ptqa.test_id= :test_id where ptq.status=0 and ptq.test_id= :test_id and ptq.d_id=" + d_ids[i].id, { replacements: { cohort_id: data.cohort_id, user_id: data.user_id, test_id: data.test_id } })
        .then(function (data) {
          return Array.from(new Set(data[0]));
        });
      let currect = [];
      currect = await practiceQues.filter(res => res.validation == "true");
      let wrong = [];
      wrong = await practiceQues.filter(res => res.validation == "false");
      let pending = [];
      pending = await practiceQues.filter(res => res.validation == "pending");

      var r = {
        d_id: d_ids[i].id,
        domain_name: d_ids[i].domin_name,
        user_id: data.user_id,
        currect: currect.length,
        panding: pending.length,
        wrong: wrong.length,
        total: currect.length + wrong.length + pending.length
      }

      if (!practiceQues) {
        reject(res.status(404).send(API._404({ message: 'Something Wrong please check' })));
      }
      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;
        });
        resolve(d);
      }
    }
  });
  res.status(200).send(API._200(await dt));
};
exports.getuserreportpracticetestAns = async (req, res) => {
  const data = await helper.decryptRequest(req.body.data);
  const pt_ids = await db.sequelize.query("SELECT pt.id,pt.practice_name,pt.type,RowNumber,case when RowNumber is not null then true  else false end ViewSummeryicon from practicetests as pt inner join cohorts as c on find_in_set(pt.id,c.practicetests) left join (SELECT MIN(test_id)RowNumber,test_id, cohort_id  FROM practice_ans where active=0 and cohort_id= :cohort_id  and user_id= :user_id group by  test_id,cohort_id)  ret on ret.test_id=pt.id and ret.cohort_id=c.id where find_in_set(" + data.user_id + ",c.userslist) and pt.status=0 and c.id= :cohort_id  group by pt.id", { replacements: { user_id: data.user_id, cohort_id: data.cohort_id } })
    .then((data) => {
      return Array.from(new Set(data[0]));
    });

  const dt = new Promise(async (resolve, reject) => {
    var d = [];
    if (pt_ids.length == 0) resolve(d);

    for (let i = 0; i < pt_ids.length; i++) {
      const ass_id = pt_ids[i];
      const practiceQues = await db.sequelize.query("SELECT * from practice_ans where cohort_id= " + data.cohort_id + " and user_id=" + data.user_id + " and active=1 and test_id=" + ass_id.id).then(function (data) {
        return Array.from(new Set(data[0]));
      });
      const Ptqa = await db.sequelize.query(`SELECT id,d_id from practiceques WHERE test_id=${ass_id.id} and status=0`).then(data => Array.from(new Set(data[0])));
      let gb = groupBy(Ptqa, 'd_id');
      let dcount = 0;
      for (let a in gb) {
        dcount++;
      }
      let currect = [];
      currect = await practiceQues.filter(res => res.correct == 1);
      let wrong = [];
      wrong = await practiceQues.filter(res => res.correct == 0);
      var c_date = await db_helper.selectByWhere('Ptestcomplate', { user_id: data.user_id, pt_id: ass_id.id, cohort_id: data.cohort_id })
      var schedule = await db_helper.selectByWhere('CohortSchedule', { type_id: ass_id.id, type: "PRACTICE", cohort_id: data.cohort_id });

      if (c_date.length > 0) {
        c_date = c_date[0].createdAt;
      } else {
        c_date = "";
      }
      var r = {
        test_id: ass_id.id,
        test_type: ass_id.type,
        practice_name: ass_id.practice_name,
        user_id: data.user_id,
        currect: currect.length,
        panding: Ptqa.length - (currect.length + wrong.length),
        wrong: wrong.length,
        domains: dcount,
        c_date,
        schedule,
        total: currect.length + wrong.length + (Ptqa.length - (currect.length + wrong.length)),
        ViewSummeryicon: ass_id.ViewSummeryicon,
        RowNumber: 0//ass_id.RowNumber
      };

      let ab = await r;
      d.push(ab);
      if (i == pt_ids.length - 1) {
        resolve(d);
      }
    }
  });
  res.status(200).send(API._200(await dt));
};
exports.practice_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 = "";
  var q = data.RowNumber > 0 ?
    "SELECT ptq.*,(CASE WHEN pa.ans IS NULL THEN false ELSE true end ) AS answered, pa.flag_review, pa.ans AS user_ans, pa.ans_time AS ans_time FROM (SELECT * FROM(SELECT *, @cur:= IF(PTQ_id=@id, @cur+1, 1) AS RowNumber, @id := PTQ_id FROM practice_ans t CROSS JOIN(SELECT @id:=(SELECT MIN(PTQ_id) FROM practice_ans where active=0 and cohort_id=" + data.cohort_id + " and test_id=" + data.test_id + " and user_id=" + data.user_id + " ), @cur:=0) AS init where active=0 and cohort_id=" + data.cohort_id + " and test_id=" + data.test_id + " and user_id=" + data.user_id + "  ORDER BY t.PTQ_id) A) AS pa RIGHT JOIN practiceques AS ptq ON pa.ptq_id = ptq.id WHERE Find_in_set(" + data.test_id + ", ptq.test_id) AND ptq.status = 0 AND pa.RowNumber=" + data.RowNumber + "  LIMIT " + limit + " OFFSET " + offset
    :
    "Select ptq.*,(CASE WHEN pa.ans IS NULL then false ELSE true END) as answered,pa.flag_review,pa.ans as user_ans,pa.ans_time as ans_time from (select * from practice_ans where cohort_id=" + data.cohort_id + " and user_id=" + data.user_id + " and active=1 and test_id=" + data.test_id + ") as pa RIGHT JOIN practiceques as ptq ON pa.ptq_id=ptq.id WHERE FIND_IN_SET(" + data.test_id + ",ptq.test_id) and ptq.status=0 LIMIT " + limit + " OFFSET " + offset;


  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 practiceQues = await db.sequelize.query(q)
    .then(function (data) {
      return Array.from(new Set(data[0]));
    })
  var subdomain = []
  var subdomain_array = await Subdomain.findAll({
    attributes: ['id', 'subdomain_name', 'domain_number'],
    where: {
      // id: practiceQues[i].sd_id,
      status: 0
    }
  });
  var fls = [];
  var fls_array = await Flashcard.findAll({
    where: {
      // topic_id: practiceQues[i].topic_id,
      status: 0
    },
    attributes: ['id', 'topic_id', 'term', 'definition']
  });
  var study = [];
  var study_array = await StudyMaterial.findAll({
    where: {
      // topic_id: practiceQues[i].topic_id,
      status: 0
    },
    attributes: ['id', 'topic_id', 'title', 'content']
  });
  var refers = [];
  var refers_array = await References.findAll({
    where: {
      // topic_id: practiceQues[i].topic_id,
      status: 0
    },
    include: [{
      model: Books,
      attributes: ['id', 'book_title', 'book_img']
    }]
  });
  var notes = []
  var notes_array = await QuestionNotes.findAll({
    where: {
      user_id: data.user_id,
      test_id: data.test_id,
      // q_id: practiceQues[i].id,
      test_type: 'PRACTICE',
      status: 0
    }
  });
  var video = [];
  var video_array = await db_helper.query("select topic_id,id,video_title,video_thumbnil,duration,type,topic_list,video_link from videos where status=0  order by sr_number");

  var mind = []
  var mind_array = await db_helper.query("select topic_id,id,thumbnail_link,name from mind_maps where status=0 order by sr_number");

  for (let i = 0; i < practiceQues.length; i++) {
    fls = fls_array.filter(x => x.topic_id == practiceQues[i].topic_id)
    subdomain = subdomain_array.filter(x => x.id == practiceQues[i].sd_id)
    study = study_array.filter(x => x.topic_id == practiceQues[i].topic_id)
    refers = refers_array.filter(x => x.topic_id == practiceQues[i].topic_id)
    notes = notes_array.filter(x => x.q_id == practiceQues[i].id)
    video = video_array[0].filter(item => item.topic_id && item.topic_id.includes(practiceQues[i].topic_id));
    mind = mind_array[0].filter(item => item.topic_id && item.topic_id.includes(practiceQues[i].topic_id));
    if (!video) {
      video = []
    }
    if (!mind) {
      mind = []
    }

    var Topicdes = [];
    Topicdes = await Topic.findAll({
      where: {
        id: practiceQues[i].topic_id,
        status: 0
      },
      attributes: ['id', 'topic_name', 'sr_number']
    });
    practiceQues[i].Flashcards = fls;
    practiceQues[i].StudyMaterials = study;
    practiceQues[i].Video = video;
    practiceQues[i].References = refers;
    practiceQues[i].MindMaps = mind;
    practiceQues[i].Topic = Topicdes;
    practiceQues[i].SubDomains = subdomain;
    practiceQues[i].Notes = notes.length > 0 ? notes[0].notes : "";
    practiceQues[i].MindMapsAccess = cohort_data[0][0].mindmap_access;
    practiceQues[i].ReferencesAccess = cohort_data[0][0].reference_access;
    practiceQues[i].VideoAccess = cohort_data[0][0].video_access;
    practiceQues[i].StudyMaterialsAccess = cohort_data[0][0].summary_access;
    practiceQues[i].FlashcardAccess = cohort_data[0][0].flashcard_access;
  }
  if (!practiceQues) {
    res.status(404).send(API._404({ message: 'no Data found' }));
  }
  res.status(200).send(API._200(await practiceQues.sort((a, b) => a.id - b.id)));
};
exports.practicecomplate = async (req, res) => {
  const data = await helper.decryptRequest(req.body.data);
  const select = await db_helper.selectByWhere('Ptestcomplate', data);
  var create;
  if (select.length == 0) {
    create = await db_helper.addData('Ptestcomplate', data);
  } else {
    res.status(400).send(API._400({ 'message': "Test Already Completed" }));
  }

  res.status(200).send(API._200(await create));
};
exports.savenotes = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const select = await db_helper.selectByWhere('Ptestcomplate', data);
  var create;
  if (select.length == 0) {
    create = await db_helper.addData('Ptestcomplate', data);
  } else {
    res.status(400).send(API._400({ 'message': "Test Already Completed" }));
  }
  const data = await db_helper.selectByWhere("QuestionNotes", { 'user_id': input.user_id, 'test_id': input.test_id, 'q_id': input.q_id, 'test_type': input.test_type })
  if (data.length > 0) {
    input["id"] = data[0].id;
    res.status(200).send(API._200(await db_helper.update("QuestionNotes", input)));
  } else {
    res.status(200).send(API._200(await db_helper.addData("QuestionNotes", input)));
  }
};
exports.filtertestques = async (req, res) => {
  const data = await helper.decryptRequest(req.body.data);
  var q = "";
  var q = data.RowNumber > 0 ?
    "SELECT ptq.*,(CASE WHEN pa.ans IS NULL THEN false ELSE true end ) AS answered, pa.flag_review, pa.ans AS user_ans, pa.ans_time AS ans_time FROM (SELECT * FROM(SELECT *, @cur:= IF(PTQ_id=@id, @cur+1, 1) AS RowNumber, @id := PTQ_id FROM practice_ans t CROSS JOIN(SELECT @id:=(SELECT MIN(PTQ_id) FROM practice_ans where active=0 and cohort_id=" + data.cohort_id + " and test_id=" + data.test_id + " and user_id=" + data.user_id + " ), @cur:=0) AS init where active=0 and cohort_id=" + data.cohort_id + " and test_id=" + data.test_id + " and user_id=" + data.user_id + "  ORDER BY t.PTQ_id) A) AS pa RIGHT JOIN practiceques AS ptq ON pa.ptq_id = ptq.id WHERE Find_in_set(" + data.test_id + ", ptq.test_id) AND ptq.status = 0 AND pa.RowNumber=" + data.RowNumber
    :
    "Select ptq.*,(CASE WHEN pa.ans IS NULL then false ELSE true END) as answered,pa.flag_review,pa.ans as user_ans,pa.ans_time as ans_time from (select * from practice_ans where cohort_id=" + data.cohort_id + " and user_id=" + data.user_id + " and active=1 and test_id=" + data.test_id + ") as pa RIGHT JOIN practiceques as ptq ON pa.ptq_id=ptq.id WHERE FIND_IN_SET(" + data.test_id + ",ptq.test_id) and ptq.status=0";

  for (const [key, value] of Object.entries(data)) {
    if (key != "test_id" && key != "user_id" && key != "cohort_id" && key != "RowNumber") {
      q += " and ptq." + 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 practiceQues = await db.sequelize.query(q)
    .then(function (data) {
      return Array.from(new Set(data[0]));
    })
  var subdomain = []
  var subdomain_array = await Subdomain.findAll({
    attributes: ['id', 'subdomain_name', 'domain_number'],
    where: {
      status: 0
    }
  });
  var fls = [];
  var fls_array = await Flashcard.findAll({
    where: {
      status: 0
    },
    attributes: ['id', 'topic_id', 'term', 'definition']
  });
  var study = [];
  var study_array = await StudyMaterial.findAll({
    where: {
      status: 0
    },
    attributes: ['id', 'topic_id', 'title', 'content']
  });
  var refers = [];
  var refers_array = await References.findAll({
    where: {
      status: 0
    },
    include: [{
      model: Books,
      attributes: ['id', 'book_title', 'book_img']
    }]
  });
  var notes = []
  var notes_array = await QuestionNotes.findAll({
    where: {
      user_id: data.user_id,
      test_id: data.test_id,
      test_type: 'PRACTICE',
      status: 0
    }
  });
  var video = [];
  var video_array = await db_helper.query("select topic_id,id,video_title,video_thumbnil,duration,type,topic_list,video_link from videos where status=0  order by sr_number");

  var mind = []
  var mind_array = await db_helper.query("select topic_id,id,thumbnail_link,name from mind_maps where status=0 order by sr_number");

  for (let i = 0; i < practiceQues.length; i++) {
    fls = fls_array.filter(x => x.topic_id == practiceQues[i].topic_id)
    subdomain = subdomain_array.filter(x => x.id == practiceQues[i].sd_id)
    study = study_array.filter(x => x.topic_id == practiceQues[i].topic_id)
    refers = refers_array.filter(x => x.topic_id == practiceQues[i].topic_id)
    notes = notes_array.filter(x => x.q_id == practiceQues[i].id)
    video = video_array[0].filter(item => item.topic_id && item.topic_id.includes(practiceQues[i].topic_id));
    mind = mind_array[0].filter(item => item.topic_id && item.topic_id.includes(practiceQues[i].topic_id));
    if (!video) {
      video = []
    }
    if (!mind) {
      mind = []
    }

    var Topicdes = [];
    Topicdes = await Topic.findAll({
      where: {
        id: practiceQues[i].topic_id,
        status: 0
      },
      attributes: ['id', 'topic_name', 'sr_number']
    });
    practiceQues[i].Flashcards = fls;
    practiceQues[i].StudyMaterials = study;
    practiceQues[i].Video = video;
    practiceQues[i].References = refers;
    practiceQues[i].MindMaps = mind;
    practiceQues[i].Topic = Topicdes;
    practiceQues[i].SubDomains = subdomain;
    practiceQues[i].Notes = notes.length > 0 ? notes[0].notes : "";
    practiceQues[i].MindMapsAccess = cohort_data[0][0].mindmap_access;
    practiceQues[i].ReferencesAccess = cohort_data[0][0].reference_access;
    practiceQues[i].VideoAccess = cohort_data[0][0].video_access;
    practiceQues[i].StudyMaterialsAccess = cohort_data[0][0].summary_access;
    practiceQues[i].FlashcardAccess = cohort_data[0][0].flashcard_access;
  }
  if (!practiceQues) {
    res.status(404).send(API._404({ message: 'No data found' }));
  }
  res.status(200).send(API._200(await practiceQues.sort((a, b) => a.id - b.id)));
};
exports.getcohortsuserallexam = async (req, res) => {
  const data = await helper.decryptRequest(req.body.data);
  const examlist = await db.sequelize.query(
    `select coh.id cohort_id,coh.cohort_name,coh.knowassessments,coh.practicetests,coh.ketexamtests, ka.id type_id,ka.knowass_name exam_name,'KA' type ,coh.certi_id,` + data.user_id + ` user_id
                            from cohorts coh 
                            inner join knowledge_asses ka on find_in_set(ka.id,knowassessments)>0 
                        where find_in_set(`+ data.user_id + `,userslist) and coh.status=0 
                    union all 
                    select coh.id cohort_id,coh.cohort_name,coh.knowassessments,coh.practicetests,coh.ketexamtests, pt.id type_id,pt.practice_name exam_name,'PT' type ,coh.certi_id,`+ data.user_id + ` user_id
                            from cohorts coh 
                            inner join practicetests pt on find_in_set(pt.id,practicetests)>0
                        where find_in_set(`+ data.user_id + `,userslist) and coh.status=0 
                    union all 
                    select coh.id cohort_id,coh.cohort_name,coh.knowassessments,coh.practicetests,coh.ketexamtests, cat.id type_id,cat.ketexam_name exam_name,'CAT' type ,coh.certi_id,`+ data.user_id + ` user_id
                            from cohorts coh 
                        inner join ketexamtests cat on find_in_set(cat.id,ketexamtests)>0 
                        where find_in_set(`+ data.user_id + `,userslist) and coh.status=0; 
                        select * from users where id=`+ data.user_id)
    .then(function (data) {
      return Array.from(new Set(data[0]));
    })
  res.status(200).send(API._200(await examlist));
};
exports.practiceAppQueById = async (req, res) => {
  const practiceAppqueId = await helper.decryptUri(req.params.id)
  const practiceAppque = await PracticeAppque.findOne({
    where: {
      id: practiceAppqueId,
      status: 0,
    },
    include: [{
      model: Domain,
      attributes: ['id', 'domin_name']
    }, {
      model: Subdomain,
      attributes: ['id', 'subdomain_name']
    }, {
      model: Topic,
      attributes: ['id', 'topic_name']
    }, {
      model: Certificate,
      attributes: ['id', 'certificate_name']
    }]
  });
  if (!practiceAppque) {
    res.status(404).send(API._404({ message: `PracticeAppque with id: ${practiceAppqueId} was not found` }));
  }
  res.status(200).send(API._200(await practiceAppque));
};
exports.addPracticeAppque = async (req, res) => {
  const data = await helper.decryptRequest(req.body.data);
  const practiceAppque = await PracticeAppque.create(data);
  res.status(200).send(API._200(await practiceAppque));
};
exports.getAllPracticeAppque = async (req, res) => {
  const practiceAppque = PracticeAppque.findAll({
    where: {
      status: 0
    },
    include: [{
      model: Domain,
      attributes: ['id', 'domin_name']
    }, {
      model: Subdomain,
      attributes: ['id', 'subdomain_name']
    }, {
      model: Topic,
      attributes: ['id', 'topic_name']
    }, {
      model: Certificate,
      attributes: ['id', 'certificate_name']
    }, {
      model: Cource,
      attributes: ['id', 'course_name']
    }]
  });
  res.status(200).send(API._200(await practiceAppque));
};

exports.deletePracticeAppque = async (req, res) => {
  const practiceAppqueId = await helper.decryptUri(req.params.id)
  const practiceAppque = await PracticeAppque.findByPk(practiceAppqueId).then(async res1 => {
    res1.set("status", 1);
    return await res1.save();
  })
  if (!practiceAppque) {
    res.status(404).send(API._404({ message: `PracticeAppque with id: ${practiceAppqueId} was not found` }));
  }
  res.status(200).send(API._200(await practiceAppque));
};
exports.updatePracticeAppque = async (req, res) => {
  const id = await helper.decryptUri(req.params.id)
  const practiceAppque = await PracticeAppque.findByPk(id)
  if (!practiceAppque) {
    res.status(404).send(API._404({ message: `PracticeAppque with id: ${id} was not found` }));
  }
  if (input.free_paid) practiceAppque.free_paid = input.free_paid
  if (input.title) practiceAppque.title = input.title
  if (input.first_choice) practiceAppque.first_choice = input.first_choice
  if (input.second_choice) practiceAppque.second_choice = input.second_choice
  if (input.third_choice) practiceAppque.third_choice = input.third_choice
  if (input.fourth_choice) practiceAppque.fourth_choice = input.fourth_choice
  if (input.type) practiceAppque.type = input.type
  if (input.explanation) practiceAppque.explanation = input.explanation
  if (input.answer) practiceAppque.answer = input.answer
  if (input.d_id) practiceAppque.d_id = input.d_id
  if (input.sd_id) practiceAppque.sd_id = input.sd_id
  if (input.certi_id) practiceAppque.certi_id = input.certi_id
  if (input.cource_id) practiceAppque.cource_id = input.cource_id
  if (input.topic_id) practiceAppque.topic_id = input.topic_id
  if (input.subtopic_id) practiceAppque.subtopic_id = input.subtopic_id
  if (input.ref_link) practiceAppque.ref_link = input.ref_link
  if (input.youtube_link) practiceAppque.youtube_link = input.youtube_link
  if (input.bookpage_no) practiceAppque.bookpage_no = input.bookpage_no
  if (input.blog_url) practiceAppque.blog_url = input.blog_url
  if (input.status) practiceAppque.status = input.status

  res.status(200).send(API._200(await practiceAppque.save()));
};


exports.practiceQueById = async (req, res) => {
  const practicequeId = await helper.decryptUri(req.params.id)
  const practiceque = await Practiceque.findOne({
    where: {
      id: practicequeId,
      status: 0,
    },
    include: [{
      model: Domain,
      attributes: ['id', 'domin_name']
    }, {
      model: Subdomain,
      attributes: ['id', 'subdomain_name']
    }, {
      model: Topic,
      attributes: ['id', 'topic_name']
    }, {
      model: Practicetest,
      attributes: ['id', 'practice_name']
    }]
  });
  if (!practiceque) {
    res.status(404).send(API._404({ message: `practiceque with id: ${practicequeId} was not found` }));
  }
  res.status(200).send(API._200(await practiceque));
};
exports.deletePracticeQue = async (req, res) => {
  const practiceAppId = await helper.decryptUri(req.params.id)
  const pq = await Practiceque.findByPk(practiceAppId).then(async res1 => {
    res1.set("status", 1);
    return await res1.save();
  })
  if (!pq) {
    res.status(404).send(API._404({ message: `pq with id: ${practiceAppId} was not found` }));
  }
  res.status(200).send(API._200(await pq));
};
exports.updatePracticeQue = async (req, res) => {
  const id = await helper.decryptUri(req.params.id)
  const practiceque = await Practiceque.findByPk(id)
  if (!practiceque) {
    res.status(404).send(API._404({ message: `practiceque with id: ${id} was not found` }));
  }
  if (input.test_id) practiceque.test_id = input.test_id
  if (input.title) practiceque.title = input.title
  if (input.first_choice) practiceque.first_choice = input.first_choice
  if (input.second_choice) practiceque.second_choice = input.second_choice
  if (input.third_choice) practiceque.third_choice = input.third_choice
  if (input.fourth_choice) practiceque.fourth_choice = input.fourth_choice
  if (input.type) practiceque.type = input.type
  if (input.d_id) practiceque.d_id = input.d_id
  if (input.sd_id) practiceque.sd_id = input.sd_id
  if (input.topic_id) practiceque.topic_id = input.topic_id
  if (input.subtopic_id) practiceque.subtopic_id = input.subtopic_id
  if (input.ref_link) practiceque.ref_link = input.ref_link
  if (input.youtube_link) practiceque.youtube_link = input.youtube_link
  if (input.bookpage_no) practiceque.bookpage_no = input.bookpage_no
  if (input.blog_url) practiceque.blog_url = input.blog_url
  if (input.status) practiceque.status = input.status
  if (input.point) practiceque.point = input.point
  if (input.certi_id) practiceque.point = input.certi_id
  if (input.description) practiceque.description = input.description
  res.status(200).send(API._200(await practiceque.save()));
};
exports.addPracticeQue = async (req, res) => {
  const data = await helper.decryptRequest(req.body.data);
  const pq = await Practiceque.create(data);
  res.status(200).send(API._200(await pq));
};
exports.getAllPracticeQue = async (req, res) => {
  const practiceque = Practiceque.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']
    }, {
      model: Practicetest,
      attributes: ['id', 'practice_name']
    }]
  });
  res.status(200).send(API._200(await practiceque));
};


exports.practiceTestById = async (req, res) => {
  const practicetestId = await helper.decryptUri(req.params.id)
  let practice = await new Promise(async (resolve, reject) => {
    Practicetest.findOne({
      where: {
        status: 0,
        id: practicetestId,
      },
      include: [{
        model: Certificate,
        attributes: ['id', 'certificate_name']
      }]
    }).then(async (res) => {
      if (!res) { resolve([]) };
      const course_ids = await res.get('course_id');
      const acronums = await res.get('acronums');
      res = res.toJSON()
      let data = [];
      let acron = [];
      if (course_ids.length > 0) {
        data = await Cource.findAll({
          attributes: ['id', 'course_name'],
          where: {
            status: 0,
            id: course_ids
          }
        });
      }
      if (acronums.length > 0) {
        acron = await Acronyms.findAll({
          attributes: ['id', 'short_name', 'full_name'],
          where: {
            status: 0,
            id: acronums
          }
        });
      }
      if (data.length > 0) {
        res.course = data.map((a) => a.toJSON())
      } else {
        res.course = [];
      }
      res.acronum_ids = acronums;
      if (acron.length > 0) {
        res.acronums = acron.map((a) => a.toJSON())
      } else {
        res.acronums = [];
      }
      resolve(res);
    })
  }).catch((ex) => {
    res.status(404).send(API._404({ message: `Practice test was not found` }));
  });
  res.status(200).send(API._200(await practice));
};
exports.deletePracticeTest = async (req, res) => {
  const practiceAppId = await helper.decryptUri(req.params.id)
  const pq = await Practicetest.findByPk(practiceAppId).then(async res1 => {
    res1.set("status", 1);
    return await res1.save();
  })
  if (!pq) {
    res.status(404).send(API._404({ message: `Test with id: ${practiceAppId} was not found` }));
  }
  res.status(200).send(API._200(await pq));
};
exports.updatePracticeTest = async (req, res) => {
  const id = await helper.decryptUri(req.params.id)
  const practicetest = await Practicetest.findByPk(id)
  if (!practicetest) {
    res.status(404).send(API._404({ message: `practiceque with id: ${id} was not found` }));
  }
  if (input.practice_name) practicetest.practice_name = input.practice_name
  if (input.certi_id) practicetest.certi_id = input.certi_id
  if (input.course_id) practicetest.course_id = input.course_id
  if (input.status) practicetest.status = input.status
  if (input.time) practicetest.time = input.time
  if (input.acronums) practicetest.acronums = input.acronums
  if (input.type) practicetest.type = input.type
  if (input.description) practicetest.description = input.description
  res.status(200).send(API._200(await practicetest.save()));
};
exports.addPracticeTest = async (req, res) => {
  const data = await helper.decryptRequest(req.body.data);
  const pq = await Practicetest.create(data);
  res.status(200).send(API._200(await pq));
};
