const db = require("../models");
const API = require('../helper/API_Response');
const db_helper = require("../helper/db_helper");
const helper = require("../helper/helper");
const { MindMap, StudyMaterial, Practiceque, Practicetest, Video, Flashcard, Domain, Subdomain, Topic, Certificate, Cource } = require("../models");

exports.by_cource = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  var is_change_certi = false;
  const domains = await Domain.findAll({
    attributes: ['id', 'domin_name'],
    where: {
      status: 0,
      certi_id: input.c_id
    }
  });
  const cert = await Certificate.findAll({
    attributes: ['id', 'certificate_name', 'short_name'],
    where: {
      status: 0,
      id: input.c_id
    }
  });

  var dom = [];
  var i = 0;
  while (i < domains.length) {
    const subdomains = await db.sequelize.query("select id,subdomain_name,domain_number from subdomains where status=0 and d_id=" + domains[i].id + " ORDER BY 1*SUBSTRING_INDEX(domain_number, '.', 1) ASC,1*SUBSTRING_INDEX(domain_number, '.', -1) ASC")
      .then(function (data) {
        return Array.from(new Set(data[0]));
      });
    var subdom = [];
    var j = 0;
    while (j < subdomains.length) {
      const all = await db.sequelize.query("select * from videos where status=0 and find_in_set(" + subdomains[j].id + ",sd_id) order by sr_number desc")
        .then(function (data) {
          return Array.from(new Set(data[0]));
        });
      if (all.length > 0) {
        let vid = [];
        for (let v = 0; v < all.length; v++) {
          var already = await db_helper.selectByWhere('VideoMindView', { type_id: all[v].id, type: "VIDEO", cohort_id: input.cohort_id, user_id: input.user_id });
          vid.push({
            "id": all[v].id,
            "sd_id": subdomains[j].id,
            "d_id": domains[i].id,
            "video_link": all[v].video_link,
            "transcript_link": all[v].transcript_link,
            "video_title": all[v].video_title,
            "video_thumbnil": all[v].video_thumbnil,
            "type": all[v].type,
            "video_type": all[v].video_type,
            "duration": all[v].duration,
            "video_lesson_link_144p": all[v].video_lesson_link_144p,
            "video_lesson_link_240p": all[v].video_lesson_link_240p,
            "video_lesson_link_360p": all[v].video_lesson_link_360p,
            "video_lesson_link_480p": all[v].video_lesson_link_480p,
            "video_lesson_link_720p": all[v].video_lesson_link_720p,
            "viewed": already.length > 0 ? (already[0].is_completed == 1 ? true : false) : false,
            "view_percent": already.length > 0 ? already[0].view_percent : 0, //all[v].viewed_users.includes(input.user_id),
            "chapters": all[v].chapters ? JSON.parse(all[v].chapters) : [],
            "is_change_certi": is_change_certi
          })
        }
        subdom.push({ "id": subdomains[j].id, "subdomain_name": subdomains[j].subdomain_name, "domain_number": subdomains[j].domain_number, "Videos": vid });
      }
      j++;
    }
    if (subdom.length > 0) {
      dom.push({ "id": domains[i].id, "domin_name": domains[i].domin_name, "SubDomains": subdom });
    }
    i++;
  }
  let result = { "Certificates": cert, "Domains": dom };
  res.status(200).send(API._200(await result));
};
exports.noteadd = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const data = await db_helper.selectByWhere('VideoNotes', { 'user_id': input.user_id, 'video_id': input.video_id })
  if (data.length > 0) {
    input["id"] = data[0].id;
    res.status(200).send(API._200(await db_helper.update('VideoNotes', input)));
  } else {
    res.status(200).send(API._200(await db_helper.addData('VideoNotes', input)));
  }
};
exports.noteby_user = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  res.status(200).send(API._200(await db_helper.selectByWhere('VideoNotes', { 'user_id': input.id, 'notes_type': input.notes_type, 'video_id': input.video_id })));
};
exports.search = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const flashcard = await Flashcard.findAll({
    where: {
      status: 0,
      certi_id: input.certi_id
    },
    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']
    }]
  });
  const all = await db.sequelize.query("select mm.id,mm.topic_id,mm.bkp_sd_id,mm.video_title,mm.video_thumbnil,certificate,domain,CONCAT('[',GROUP_CONCAT(DISTINCT subdomain),']')subdomain,CONCAT('[',GROUP_CONCAT(DISTINCT topics),']')topics from videos mm left join (select GROUP_CONCAT(CONCAT_ws('','{\"id\":', id,',\"certificate_name\":\"', certificate_name),'\"}' order by id) certificate,id from certificates group by id) c on mm.certi_id=c.id left join (select GROUP_CONCAT(CONCAT_ws('','{\"id\":', id,',\"domin_name\":\"', domin_name),'\"}' order by id) domain,id from domains group by id) d on d.id=mm.d_id left join (select GROUP_CONCAT(CONCAT_ws('','{\"id\":', id,',\"subdomain_name\":\"', subdomain_name),'\"}'order by id)subdomain,d_id,id from subdomains group by id) sd on find_in_set(sd.id,mm.sd_id)>0 and sd.d_id=mm.d_id left join (select GROUP_CONCAT(CONCAT_ws('','{\"id\":', id,',\"topic_name\":\"', topic_name),'\"}' order by id)topics,id from topics group by id)top on find_in_set(top.id,mm.topic_id)>0 where  mm.status=0  group by mm.id;")
    .then(function (data) {
      return Array.from(new Set(data[0]));
    });
  for (let i = 0; i < all.length; i++) {
    all[i].certificate = JSON.parse(all[i].certificate);
    all[i].domain = JSON.parse(all[i].domain);
    all[i].subdomain = JSON.parse(all[i].subdomain);
    all[i].topics = JSON.parse(all[i].topics);
    all[i].topic_id = all[i].topic_id ? all[i].topic_id.split(",") : [];
    all[i].bkp_sd_id = all[i].bkp_sd_id ? all[i].bkp_sd_id.split(",") : [];
    // all[i].sd_id = all[i].sd_id ? all[i].sd_id.split(",") : [];
  }

  const practiceque = await Practiceque.findAll({
    where: {
      status: 0,
      certi_id: input.certi_id
    },
    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']
    }]
  });
  const maps = await db.sequelize.query(`select mm.id,mm.thumbnail_link,mm.video_link,mm.name,mm.bkp_sd_id,mm.topic_id,mm.sd_id,GROUP_CONCAT(CONCAT_ws('','{\"id\":', c.id,',\"certificate_name\":\"', certificate_name),'\"}' )certificate,GROUP_CONCAT(CONCAT_ws('','{\"id\":', d.id,',\"domin_name\":\"', domin_name),'\"}' )domain,GROUP_CONCAT(CONCAT_ws('','{\"id\":', sd.id,',\"subdomain_name\":\"', subdomain_name),'\"}')subdomain from mind_maps mm left join certificates c on mm.certi_id=c.id left join domains d on d.id=mm.d_id left join subdomains sd on sd.id=mm.sd_id and sd.d_id=mm.d_id where mm.certi_id=${input.certi_id} and  mm.status=0 group by mm.id`)
    .then(function (data) {
      return Array.from(new Set(data[0]));
    });
  if (maps.length > 0) {
    for (let i = 0; i < maps.length; i++) {
      maps[i].certificate = JSON.parse(maps[i].certificate);
      maps[i].domain = JSON.parse(maps[i].domain);
      maps[i].subdomain = JSON.parse(maps[i].subdomain);
      maps[i].topic_id = maps[i].topic_id != "" ? maps[i].topic_id.split(",") : [];
      maps[i].bkp_sd_id = maps[i].bkp_sd_id != "" ? maps[i].bkp_sd_id.split(",") : [];
      maps[i].sd_id = maps[i].sd_id != "" ? maps[i].sd_id.split(",") : [];
    }
  }

  const study = await StudyMaterial.findAll({
    where: {
      certi_id: input.certi_id,
      status: 0
    }
  });
  const data = [];
  data.push({ 'FlashCards': flashcard, 'Videos': all, 'PracticeQuestions': practiceque, "MindMaps": maps, "Study": study })

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

exports.update_view = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  var already = await db_helper.selectByWhere('VideoMindView', { type_id: input.type_id, type: "VIDEO", cohort_id: input.cohort_id, user_id: input.user_id });
  if (already.length <= 0)
    return API._200(await db_helper.addData('VideoMindView', input));
  else {
    if (parseInt(input.view_percent) >= parseInt(already[0].view_percent)) {
      input['id'] = already[0].id;
      res.status(200).send(API._200(await db_helper.update('VideoMindView', input)));
    }
    else {
      res.status(200).send(API._200(await db_helper.selectByWhere('VideoMindView', { type_id: input.type_id, type: "VIDEO", cohort_id: input.cohort_id, user_id: input.user_id })));
    }
  }

};
exports.add = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  res.status(200).send(API._200(await db_helper.addData('Video', input)));
};
exports.all = async (req, res) => {
  const all = await db.sequelize.query("select mm.*,certificate,domain,CONCAT('[',GROUP_CONCAT(DISTINCT subdomain),']')subdomain,CONCAT('[',GROUP_CONCAT(DISTINCT topics),']')topics from videos mm left join (select GROUP_CONCAT(CONCAT_ws('','{\"id\":', id,',\"certificate_name\":\"', certificate_name),'\"}' order by id) certificate,id from certificates group by id) c on mm.certi_id=c.id left join (select GROUP_CONCAT(CONCAT_ws('','{\"id\":', id,',\"domin_name\":\"', domin_name),'\"}' order by id) domain,id from domains group by id) d on d.id=mm.d_id left join (select GROUP_CONCAT(CONCAT_ws('','{\"id\":', id,',\"subdomain_name\":\"', subdomain_name),'\"}'order by id)subdomain,d_id,id from subdomains group by id) sd on find_in_set(sd.id,mm.sd_id)>0 and sd.d_id=mm.d_id left join (select GROUP_CONCAT(CONCAT_ws('','{\"id\":', id,',\"topic_name\":\"', topic_name),'\"}' order by id)topics,id from topics group by id)top on find_in_set(top.id,mm.topic_id)>0 where  mm.status=0  group by mm.id;")
    .then(function (data) {
      return Array.from(new Set(data[0]));
    });
  if (all.length == 0) {
    res.status(200).send(API._200([]));
  }
  const allnotes = await db_helper.allData('VideoNotes');
  for (let i = 0; i < all.length; i++) {
    all[i].certificate = JSON.parse(all[i].certificate);
    all[i].domain = JSON.parse(all[i].domain);
    all[i].subdomain = JSON.parse(all[i].subdomain);
    all[i].topics = JSON.parse(all[i].topics);
    all[i].topic_id = all[i].topic_id ? all[i].topic_id.split(",") : [];
    all[i].bkp_sd_id = all[i].bkp_sd_id ? all[i].bkp_sd_id.split(",") : [];
    all[i].sd_id = all[i].sd_id ? all[i].sd_id.toString().split(",") : [];
    all[i].notes = allnotes.filter((res) => res.video_id == all[i].id);
  }
  res.status(200).send(API._200(await all));
};

exports.delete = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  res.status(200).send(API._200(await db_helper.statusChange('Video', input.id)));
};
exports.update = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  res.status(200).send(API._200(await db_helper.update('Video', input)));
};
exports.save_rearrange = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  let data = input.videos;
  let response = [];
  for (let i = 0; i < data.length; i++) {
    response = await db_helper.update('Video', data[i])
  }
  res.status(200).send(API._200(await response));
};