const db = require("../models");
const API = require('../helper/API_Response');
const db_helper = require("../helper/db_helper");
const helper = require("../helper/helper");
const { Domain } = require("../models");


exports.allmaps = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const all = await Domain.findAll({
    attributes: ['id', 'domin_name', 'domain_number'],
    where: {
      status: 0,
      certi_id: input.certi_id
    }
  });
  let data = [];
  for (let j = 0; j < all.length; j++) {
    let mind = [];
    mind = await db.sequelize.query("select * from mind_maps where status=0 and d_id=" + all[j].id + " order by sr_number")
      .then(function (data) {
        return Array.from(new Set(data[0]));
      });
    // }
    if (mind.length > 0) {
      let mindmaps = [];
      for (let i = 0; i < mind.length; i++) {
        var already = await db_helper.selectByWhere('VideoMindView', { type_id: mind[i].id, type: "MIND", cohort_id: input.cohort_id, user_id: input.user_id });
        mindmaps.push({
          "id": mind[i].id,
          "name": mind[i].name,
          "d_id": mind[i].d_id,
          "sd_id": mind[i].sd_id,
          "description": mind[i].description,
          "createdAt": mind[i].createdAt,
          "viewed": already.length > 0 ? true : false,
          "transcript": mind[i].transcript,
          "chapters": mind[i].chapters ? JSON.parse(mind[i].chapters) : [],
          "video_link": mind[i].video_link,
          "thumbnail_link": mind[i].thumbnail_link,
          "video_link_720p": mind[i].video_link_720p,
          "video_link_480p": mind[i].video_link_480p,
          "video_link_360p": mind[i].video_link_360p,
          "video_link_240p": mind[i].video_link_240p,
          "video_link_144p": mind[i].video_link_144p,
          "Flashcards": [],//respo[0][1],
          "StudyMaterials": [],//respo[0][2],
          "Video": [],//respo[0][0],
          "References": []
        })
      }
      await data.push({
        "id": all[j].id,
        "domin_name": all[j].domin_name,
        "domain_number": all[j].domain_number,
        "MindMaps": mindmaps
      })
    }
  }
  res.status(200).send(API._200(await data));
};
exports.updateviewer = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  var already = await db_helper.selectByWhere('VideoMindView', { type_id: input.type_id, type: "MIND", 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: "MIND", cohort_id: input.cohort_id, user_id: input.user_id })));
    }
  }
};

exports.add = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  input['bkp_sd_id'] = '1,1';
  res.status(200).send(API._200(await db_helper.addData('MindMap', input)));
};
exports.delete = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  res.status(200).send(API._200(await db_helper.statusChange('MindMap', input.id)));
};
exports.all = async (req, res) => {
  const all = await db.sequelize.query("select mm.*,certificate,domain,CONCAT('[',GROUP_CONCAT(subdomain),']')subdomain from mind_maps mm left join (select CONCAT(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 CONCAT(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 where  mm.status=0  group by mm.id;")
    .then(function (data) {
      return Array.from(new Set(data[0]));
    });
  if (all.length > 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].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(",") : [];
    }
  }
  res.status(200).send(API._200(await all));
};
exports.save_rearrange = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  let data = input.mindmaps;
  let response = [];
  for (let i = 0; i < data.length; i++) {
    response = await db_helper.update('MindMap', data[i])
  }
  res.status(200).send(API._200(await response));
};
exports.update = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  res.status(200).send(API._200(await db_helper.update('MindMap', input)));
};