const db = require("../models");
const API = require('../helper/API_Response');
const db_helper = require("../helper/db_helper");
const helper = require("../helper/helper");
const { Templates, Domain, TemplateSchedule, Certificate, CohortSchedule, Cohort, Cource, KnowledgeAsses, Practicetest, Ketexamtest, HybridTemplates, HybridTemplatesSchedule } = require("../models");

exports.add = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  var err = [];
  var data = {
    "name": input.name,
    "certi_id": input.certi_id,
    "knowassessments": input.knowassessments,
    "practicetests": input.practicetests,
    "ketexamtests": input.ketexamtests,
    "flashcard_app": input.flashcard_app,
    "practice_que_app": input.practice_que_app,
    "events": input.tevents,
    "email_templates": input.email_templates,
    "cohortIds": "",
    "video_access": input.video_access,
    "mindmap_access": input.mindmap_access,
    "summary_access": input.summary_access,
    "reference_access": input.reference_access,
    "KA_access": input.KA_access,
    "PT_access": input.PT_access,
    "CAT_access": input.CAT_access,
    "livechat_access": input.livechat_access,
    "liveq_access": input.liveq_access,
    "liveevent_access": input.liveevent_access,
    "start_date": input.start_date,
    "flashcard_access": input.flashcard_access,
    "question_access": input.question_access,
    "videos": input.videos,
    "mindmaps": input.mindmaps,
    "live_events": input.live_events,
    "baseline_ka": input.baseline_ka,
    "baseline_ka_schedule": input.baseline_ka_schedule

  };
  const template = await Templates.create(data).catch((ex) => err = ex.errors[0]);
  if (input.schedule) {
    let schedule = input.schedule
    let template_id = template.id;
    for (let i = 0; i < schedule.length; i++) {
      schedule[i].template_id = template_id;
      await TemplateSchedule.create(schedule[i]).catch((ex) => err = ex.errors[0]);
    }
  }
  if (err.length > 0) {
    res.status(404).send(API._404({ message: err.message }));
  }
  res.status(200).send(API._200(await template));
};
exports.all = async (req, res) => {
  const result = await Templates.findAll({
    where: {
      status: 0
    },
    include: [{
      model: Certificate,
      attributes: ['id', 'certificate_name']
    }]
  })
  if (result.length > 0) {
    for (let j = 0; j < result.length; j++) {
      result[j] = result[j].toJSON()
      const knowassessments = await result[j].knowassessments;
      const practicetests = await result[j].practicetests;
      const cattests = await result[j].ketexamtests;
      const email_templates = await result[j].email_templates;
      const videos = await result[j].videos;
      const mindmaps = await result[j].mindmaps;

      if (videos != "") {
        let data1 = await db_helper.query("select id,video_title from videos where id in(" + videos + ")");
        result[j].videos = data1[0];
        let eschedule = await db_helper.query("select * from templates_schedules where type_id in(" + videos + ") and template_id=" + result[j].id + " and type='video'");
        result[j].video_schedule = eschedule[0];
      } else {
        result[j].videos = [];
        result[j].video_schedule = [];
      }
      if (mindmaps != "") {
        let data1 = await db_helper.query("select id,name from mind_maps where id in(" + mindmaps + ")");
        result[j].mindmaps = data1[0];
        let eschedule = await db_helper.query("select * from templates_schedules where type_id in(" + mindmaps + ") and template_id=" + result[j].id + " and type='mindmap'");
        result[j].mindmap_schedule = eschedule[0];
      } else {
        result[j].mindmaps = [];
        result[j].mindmap_schedule = [];
      }
      if (email_templates != "") {
        let data1 = await db_helper.query("select id,name,certi_id from email_templates where id in(" + email_templates + ")");
        result[j].email_templates = data1[0];
        let eschedule = await db_helper.query("select * from templates_schedules where type_id in(" + email_templates + ") and template_id=" + result[j].id + " and type='EMAIL'");
        result[j].email_schedule = eschedule[0];
      } else {
        result[j].email_templates = [];
        result[j].email_schedule = [];
      }
      if (knowassessments != "") {
        let data1 = await db_helper.query("select id,knowass_name from knowledge_asses where id in(" + knowassessments + ")");
        result[j].knowledge_asses = data1[0];
        let kschedule = await db_helper.query("select * from templates_schedules where type_id in(" + knowassessments + ") and template_id=" + result[j].id + " and type='KA'");
        result[j].knowledge_schedule = kschedule[0];
      } else {
        result[j].knowledge_asses = [];
        result[j].knowledge_schedule = [];
      }
      if (practicetests != "") {
        let data2 = await db_helper.query("select id,practice_name from practicetests where id in(" + practicetests + ")");
        result[j].practicetests = data2[0];
        let pschedule = await db_helper.query("select * from templates_schedules where type_id in(" + practicetests + ") and template_id=" + result[j].id + " and type='PRACTICE'");
        result[j].practice_schedule = pschedule[0];
      } else {
        result[j].practicetests = [];
        result[j].pschedule = [];
      }
      if (cattests != "") {
        let data3 = await db_helper.query("select id,ketexam_name from ketexamtests where id in(" + cattests + ")");
        result[j].ketexamtests = data3[0];
        let catschedule = await db_helper.query("select * from templates_schedules where type_id in(" + cattests + ") and template_id=" + result[j].id + " and type='CAT'");
        result[j].cat_schedule = catschedule[0];
      } else {
        result[j].ketexamtests = [];
        result[j].catschedule = [];
      }
    }
  }
  res.status(200).send(API._200(await result));
};
exports.addcohort = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);

  var err = [];
  var data = {
    "cohort_name": input.cohort_name,
    "certi_id": input.certi_id,
    "cource_id": input.cource_id,
    "knowassessments": input.knowassessments,
    "practicetests": input.practicetests,
    "ketexamtests": input.ketexamtests,
    "flashcard_app": input.flashcard_app,
    "practice_que_app": input.practice_que_app,
    "events": input.tevents,
    "userslist": input.userslist,
    "location": input.location,
    "email_templates": input.email_templates,
    "company_id": input.company_id,
    "time_zone": input.time_zone,
    "template_id": input.template_id,
    "video_access": input.video_access,
    "mindmap_access": input.mindmap_access,
    "summary_access": input.summary_access,
    "reference_access": input.reference_access,
    "KA_access": input.KA_access,
    "PT_access": input.PT_access,
    "CAT_access": input.CAT_access,
    "livechat_access": input.livechat_access,
    "liveq_access": input.liveq_access,
    "liveevent_access": input.liveevent_access,
    "start_date": input.start_date,
    "flashcard_access": input.flashcard_access,
    "question_access": input.question_access,
    "method_id": input.method_id,
    "access_duration": input.access_duration,
    "course_type": input.course_type,
    "videos": input.videos,
    "mindmaps": input.mindmaps,
    "live_events": input.live_events,
    "baseline_ka": input.baseline_ka,
    "baseline_ka_schedule": input.baseline_ka_schedule
  };

  const cohort = await Cohort.create(data).catch((ex) => err = ex.errors[0]);
  if (input.schedule) {
    let schedule = input.schedule
    let cohort_id = cohort.id;
    for (let i = 0; i < schedule.length; i++) {
      schedule[i].cohort_id = cohort_id;
      await CohortSchedule.create(schedule[i]).catch((ex) => err = ex.errors[0]);
    }
  }
  if (input.flashcard_app) {
    if (input.userslist) {
      await db_helper.query("update users set free_flashcard=2 where id in(" + input.userslist + ")");
    }
  }
  if (input.practice_que_app) {
    if (input.userslist) {
      await db_helper.query("update users set free_practque=2 where id in(" + input.userslist + ")");
    }
  }
  if (err.length > 0) {
    res.status(404).send(API._404({ message: err.message }));
  }
  res.status(200).send(API._200(await cohort));
};
exports.byid = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const result = await Templates.findAll({
    where: {
      id: input.id,
      status: 0
    },
    include: [{
      model: Certificate,
      attributes: ['id', 'certificate_name']
    }, {
      model: Cource,
      attributes: ['id', 'course_name']
    }]
  })
  if (result.length > 0) {
    for (let j = 0; j < result.length; j++) {
      result[j] = result[j].toJSON()
      const knowassessments = await result[j].knowassessments;
      const practicetests = await result[j].practicetests;
      const cattests = await result[j].ketexamtests;
      const cohortid = await result[j].cohortIds;

      let data1 = await KnowledgeAsses.findAll({
        attributes: ['id', 'knowass_name'],
        where: {
          status: 0,
          id: knowassessments
        }
      });
      result[j].knowledge_asses = data1.map((a) => a.toJSON())

      let data2 = await Practicetest.findAll({
        attributes: ['id', 'practice_name'],
        where: {
          status: 0,
          id: practicetests
        }
      })
      result[j].practice_tests = data2.map((a) => a.toJSON())

      let data3 = await Ketexamtest.findAll({
        attributes: ['id', 'ketexam_name'],
        where: {
          status: 0,
          id: cattests
        }
      })
      result[j].ketexam_tests = data3.map((a) => a.toJSON())

      let data4 = await Cohort.findAll({
        attributes: ['id', 'cohort_name'],
        where: {
          status: 0,
          id: cohortid
        }
      })
      result[j]["cohorts"] = data4.map((a) => a.toJSON())

    }
  }
  res.status(200).send(API._200(await result));
};
exports.delete = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const template = await Templates.findByPk(input.id)
  if (!template) {
    res.status(404).send(API._404({ message: `Template with id: ${input.id} was not found` }));
  }
  template.status = 1
  await db.sequelize.query("delete from templates_schedules where template_id= :id", { replacements: { id: input.id } })
  let result = template.save();
  res.status(200).send(API._200(await result));
};
exports.hybrid_add = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  var err = [];
  var data = {
    "name": input.name,
    "certi_id": input.certi_id,
    "knowassessments": input.knowassessments,
    "practicetests": input.practicetests,
    "ketexamtests": input.ketexamtests,
    "flashcard_app": input.flashcard_app,
    "practice_que_app": input.practice_que_app,
    "events": input.tevents,
    "email_templates": input.email_templates,
    "cohortIds": "",
    "video_access": input.video_access,
    "mindmap_access": input.mindmap_access,
    "summary_access": input.summary_access,
    "reference_access": input.reference_access,
    "KA_access": input.KA_access,
    "PT_access": input.PT_access,
    "CAT_access": input.CAT_access,
    "livechat_access": input.livechat_access,
    "liveq_access": input.liveq_access,
    "liveevent_access": input.liveevent_access,
    "start_date": input.start_date,
    "flashcard_access": input.flashcard_access,
    "question_access": input.question_access,
    "videos": input.videos,
    "mindmaps": input.mindmaps,
    "live_events": input.live_events,
    "baseline_ka": input.baseline_ka,
    "baseline_ka_schedule": input.baseline_ka_schedule

  };
  const template = await HybridTemplates.create(data).catch((ex) => err = ex.errors[0]);
  if (input.schedule) {
    let schedule = input.schedule
    let template_id = template.id;
    for (let i = 0; i < schedule.length; i++) {
      schedule[i].template_id = template_id;
      await HybridTemplatesSchedule.create(schedule[i]).catch((ex) => err = ex.errors[0]);
    }
  }
  if (err.length > 0) {
    res.status(404).send(API._404({ message: err.message }));
  }
  res.status(200).send(API._200(await template));
};

exports.hybrid_all = async (req, res) => {
  const result = await HybridTemplates.findAll({
    where: {
      status: 0
    },
    include: [{
      model: Certificate,
      attributes: ['id', 'certificate_name']
    }]
  })
  if (result.length > 0) {
    for (let j = 0; j < result.length; j++) {
      result[j] = result[j].toJSON()
      let eschedule = await db_helper.query("select * from hybrid_templates_schedules where  template_id=" + result[j].id + "");
      result[j].scheduleData = eschedule[0];
    }
  }
  res.status(200).send(API._200(await result));
};
exports.hybrid_get_save_schedule = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const sub = await HybridTemplatesSchedule.findAll({
    where: {
      template_id: input.template_id
    }
  });
  res.status(200).send(API._200(await sub));
};
exports.hybrid_update = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const tmp = await HybridTemplates.findByPk(input.id)
  if (!tmp) {
    res.status(404).send(API._404({ message: `Template with id: ${input.id} was not found` }));
  }
  if (input.name) tmp.name = input.name
  if (input.certi_id) tmp.certi_id = input.certi_id
  tmp.knowassessments = input.knowassessments
  tmp.practicetests = input.practicetests;
  tmp.ketexamtests = input.ketexamtests;
  if (input.flashcard_app) input.flashcard_app = input.flashcard_app;
  if (input.practice_que_app) input.practice_que_app = input.practice_que_app;
  if (input.status) tmp.status = input.status;
  tmp.events = input.tevents;
  tmp.email_templates = input.email_templates;
  if (input.start_date) tmp.start_date = input.start_date;
  tmp.videos = input.videos;
  tmp.mindmaps = input.mindmaps;
  tmp.baseline_ka = input.baseline_ka;
  tmp.live_events = input.live_events;
  tmp.video_access = input.video_access;
  tmp.mindmap_access = input.mindmap_access;
  tmp.summary_access = input.summary_access;
  tmp.reference_access = input.reference_access;
  tmp.KA_access = input.KA_access;
  tmp.PT_access = input.PT_access;
  tmp.CAT_access = input.CAT_access;
  tmp.livechat_access = input.livechat_access;
  tmp.liveq_access = input.liveq_access;
  tmp.liveevent_access = input.liveevent_access;
  tmp.flashcard_access = input.flashcard_access;
  tmp.question_access = input.question_access;
  tmp.baseline_ka_schedule = input.baseline_ka_schedule;

  let result = tmp.save();
  if (input.schedule) {
    await db.sequelize.query("delete from hybrid_templates_schedules where template_id= :id", { replacements: { id: input.id } })
    let schedule = input.schedule
    let template_id = input.id;
    for (let i = 0; i < schedule.length; i++) {
      schedule[i].template_id = template_id;
      await HybridTemplatesSchedule.create(schedule[i]).catch((ex) => err = ex.errors[0]);
    }
  }
  res.status(200).send(API._200(await result));
};
exports.hybridtemplatedelete = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const template = await HybridTemplates.findByPk(input.id)
  if (!template) {
    res.status(404).send(API._404({ message: `Template with id: ${input.id} was not found` }));
  }
  template.status = 1
  let result = template.save();
  await db.sequelize.query("delete from hybrid_templates_schedules where template_id= :id", { replacements: { id: input.id } })

  res.status(200).send(API._200(await result));
};
exports.update = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const tmp = await Templates.findByPk(input.id)
  if (!tmp) {
    res.status(404).send(API._404({ message: `Template with id: ${input.id} was not found` }));
  }
  if (input.name) tmp.name = input.name
  if (input.certi_id) tmp.certi_id = input.certi_id
  tmp.knowassessments = input.knowassessments
  tmp.practicetests = input.practicetests;
  tmp.ketexamtests = input.ketexamtests;
  if (input.flashcard_app) input.flashcard_app = input.flashcard_app;
  if (input.practice_que_app) input.practice_que_app = input.practice_que_app;
  if (input.status) tmp.status = input.status;
  tmp.events = input.tevents;
  tmp.email_templates = input.email_templates;
  if (input.start_date) tmp.start_date = input.start_date;
  tmp.videos = input.videos;
  tmp.mindmaps = input.mindmaps;
  tmp.baseline_ka = input.baseline_ka;
  tmp.live_events = input.live_events;
  tmp.video_access = input.video_access;
  tmp.mindmap_access = input.mindmap_access;
  tmp.summary_access = input.summary_access;
  tmp.reference_access = input.reference_access;
  tmp.KA_access = input.KA_access;
  tmp.PT_access = input.PT_access;
  tmp.CAT_access = input.CAT_access;
  tmp.livechat_access = input.livechat_access;
  tmp.liveq_access = input.liveq_access;
  tmp.liveevent_access = input.liveevent_access;
  tmp.flashcard_access = input.flashcard_access;
  tmp.question_access = input.question_access;
  tmp.baseline_ka_schedule = input.baseline_ka_schedule;

  let result = tmp.save();
  if (input.schedule) {
    await db.sequelize.query("delete from templates_schedules where template_id= :id", { replacements: { id: input.id } })
    let schedule = input.schedule
    let template_id = input.id;
    for (let i = 0; i < schedule.length; i++) {
      schedule[i].template_id = template_id;
      await TemplateSchedule.create(schedule[i]).catch((ex) => err = ex.errors[0]);
    }
  }
  res.status(200).send(API._200(await result));
};
exports.update_cohort_videomind = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  let result = [];
  await db.sequelize.query("update cohorts set videos='" + input.videos + "',mindmaps='" + input.mindmaps + "' where template_id= :template_id", { replacements: { template_id: input.template_id } })
  if (input.schedule) {
    const cohorts = await Cohort.findAll({
      attributes: ['id'],
      where: {
        template_id: input.template_id,
        status: 0
      }
    });
    let schedule = input.schedule
    for (let i = 0; i < cohorts.length; i++) {
      await db.sequelize.query("delete from cohort_schedules where cohort_id=" + cohorts[i].id + " and (type='video' or type='mindmap')")
    }
    for (let i = 0; i < schedule.length; i++) {
      for (let j = 0; j < cohorts.length; j++) {
        schedule[i].cohort_id = cohorts[j].id;
        result.push(await CohortSchedule.create(schedule[i]).catch((ex) => err = ex.errors[0]));
      }
    }
  }
  res.status(200).send(API._200(await result));
};
exports.update_domain = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const domain = await Domain.findByPk(input.id)
  if (!domain) {
    res.status(404).send(API._404({ message: `Domain with id: ${input.id} was not found` }));
  }
  if (input.domin_name) domain.domin_name = input.domin_name
  if (input.certi_id) domain.certi_id = input.certi_id
  if (input.cource_id) domain.cource_id = input.cource_id
  if (input.domain_number) domain.domain_number = input.domain_number
  if (input.status) domain.status = input.status
  res.status(200).send(API._200(await domain.save()));
};
exports.updatecohorttemp = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const tmp = await Cohort.findByPk(input.id)
  if (!tmp) {
    res.status(404).send(API._404({ message: `Cohort with id: ${input.id} was not found` }));
  }
  if (input.cohort_name) tmp.cohort_name = input.cohort_name;
  if (input.certi_id) tmp.certi_id = input.certi_id;
  if (input.cource_id) tmp.cource_id = input.cource_id;
  if (input.knowassessments) tmp.knowassessments = input.knowassessments;
  if (input.practicetests) tmp.practicetests = input.practicetests;
  if (input.ketexamtests) tmp.ketexamtests = input.ketexamtests;
  tmp.events = input.tevents;
  if (input.userslist) tmp.userslist = input.userslist;
  if (input.location) tmp.location = input.location;
  if (input.company_id) tmp.company_id = input.company_id;
  if (input.email_templates) tmp.email_templates = input.email_templates;
  if (input.time_zone) tmp.time_zone = input.time_zone;
  if (input.template_id) tmp.template_id = input.template_id;
  if (input.start_date) tmp.start_date = input.start_date;
  if (input.flashcard_access) tmp.flashcard_access = input.flashcard_access;
  if (input.question_access) tmp.question_access = input.question_access;
  if (input.method_id) tmp.method_id = input.method_id;
  if (input.access_duration) tmp.access_duration = input.access_duration;
  if (input.course_type) tmp.course_type = input.course_type;
  tmp.live_events = input.live_events ? input.live_events : "";
  if (input.videos) tmp.videos = input.videos;
  if (input.mindmaps) tmp.mindmaps = input.mindmaps;
  if (input.baseline_ka) tmp.baseline_ka = input.baseline_ka;
  tmp.video_access = input.video_access;
  tmp.mindmap_access = input.mindmap_access;
  tmp.summary_access = input.summary_access;
  tmp.reference_access = input.reference_access;
  tmp.KA_access = input.KA_access;
  tmp.PT_access = input.PT_access;
  tmp.CAT_access = input.CAT_access;
  tmp.livechat_access = input.livechat_access;
  tmp.liveq_access = input.liveq_access;
  tmp.liveevent_access = input.liveevent_access;
  tmp.flashcard_access = input.flashcard_access;
  tmp.question_access = input.question_access;
  tmp.baseline_ka_schedule = input.baseline_ka_schedule;

  let result = await tmp.save();
  if (input.schedule) {
    await db.sequelize.query("delete from cohort_schedules where cohort_id= :id", { replacements: { id: input.id } })
    let schedule = input.schedule
    let cohort_id = input.id;
    for (let i = 0; i < schedule.length; i++) {
      schedule[i].cohort_id = cohort_id;
      await CohortSchedule.create(schedule[i]).catch((ex) => err = ex.errors[0]);
    }
  }
  if (input.flashcard_app) {
    if (input.userslist) {
      await db_helper.query("update users set free_flashcard=2 where id in(" + input.userslist + ")");
    } else {
      if (tmp.userslist.length > 0)
        await db_helper.query("update users set free_flashcard=2 where id in(" + tmp.userslist.join() + ")");
    }
  } else {
    if (input.userslist) {
      await db_helper.query("update users set free_flashcard=0 where id in(" + input.userslist + ")");
    } else {
      if (tmp.userslist.length > 0)
        await db_helper.query("update users set free_flashcard=0 where id in(" + tmp.userslist.join() + ")");
    }
  }
  if (input.practice_que_app) {
    if (input.userslist) {
      await db_helper.query("update users set free_practque=2 where id in(" + input.userslist + ")");
    } else {
      if (tmp.userslist.length > 0)
        await db_helper.query("update users set free_practque=2 where id in(" + tmp.userslist.join() + ")");
    }
  } else {
    if (input.userslist) {
      await db_helper.query("update users set free_practque=0 where id in(" + input.userslist + ")");
    } else {
      if (tmp.userslist.length > 0)
        await db_helper.query("update users set free_practque=0 where id in(" + tmp.userslist.join() + ")");
    }
  }
  res.status(200).send(API._200(await result));
};