const db = require("../models");
const API = require('../helper/API_Response');
const db_helper = require("../helper/db_helper");
const helper = require("../helper/helper");
const { User, Notifications, AllLiveEvent, LiveEvents, FailedEmail } = require("../models");

exports.add = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const Op = db.Sequelize.Op;
  let all = input.data;
  let uIds = [];
  let cIds = [];
  let tIds = [];
  let tTypes = [];

  for (let i = 0; i < all.length; i++) {
    uIds.push(all[i].user_id);
    cIds.push(all[i].cohort_id);
    tIds.push(all[i].test_id);
    tTypes.push(all[i].test_type);
  }
  await Notifications.destroy({
    where: {
      user_id: {
        [Op.or]: uIds
      },
      cohort_id: {
        [Op.or]: cIds
      },
      test_id: {
        [Op.or]: tIds
      },
      test_type: {
        [Op.or]: tTypes
      },
    }
  });
  res.status(200).send(API._200(await db[input.table].bulkCreate(input.data)));
};
exports.get_setting = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const data = await db_helper.selectByWhere("NotificationSetting", { 'user_id': input.user_id })
  if (data.length > 0) {
    res.status(200).send(API._200(await data))
  } else {
    res.status(200).send(API._200(await db_helper.addData("NotificationSetting", await helper.decryptRequest(JSON.parse(event.body).data))));
  }
};
exports.markread_popup_notification = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const result = await db.sequelize.query("update notifications set is_read=1 where user_id= :user_id and cohort_id= :cohort_id and STR_TO_DATE(fire_time,'%Y-%m-%dT%H:%i:%s') <='" + input.fire_time + "' and is_read=0", { replacements: { user_id: input.user_id, cohort_id: input.cohort_id } }).then((res) => {
    return Array.from(new Set(res));
  })
  res.status(200).send(API._200(await result[0]));
};
exports.notification_all = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const result = await db.sequelize.query("select * from notifications where user_id= :user_id and cohort_id= :cohort_id and STR_TO_DATE(fire_time,'%Y-%m-%dT%H:%i:%s') <='" + input.fire_time + "' order by fire_time desc", { replacements: { user_id: input.user_id, cohort_id: input.cohort_id } }).then((result1) => {
    return Array.from(new Set(result1));
  })
  let output = result[0]
  for (let i = 0; i < output.length; i++) {
    if (output[i].test_type == 'meeting') {
      let test_id = output[i].test_id
      const all_live = await AllLiveEvent.findAll({
        where: {
          live_event_id: test_id,
          status: 0
        }
      });
      if (all_live.length > 0) {
        output[i]['end_time'] = all_live[0].end_time
        output[i]['start_time'] = all_live[0].start_time
        output[i]['meeting_time_zone'] = all_live[0].time_zone
      } else {
        const live_event = await LiveEvents.findAll({
          where: {
            id: test_id,
            status: 0
          }
        });
        if (live_event.length > 0) {
          output[i]['end_time'] = live_event[0].end_time
          output[i]['start_time'] = live_event[0].start_time
          output[i]['meeting_time_zone'] = live_event[0].time_zone
        }
      }
    }
  }
  res.status(200).send(API._200(await output));
};
exports.popup_notification = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const result = await db.sequelize.query("select * from notifications where user_id= :user_id and cohort_id= :cohort_id and STR_TO_DATE(fire_time,'%Y-%m-%dT%H:%i:%s') <='" + input.fire_time + "' and is_read=0 order by fire_time desc", { replacements: { user_id: input.user_id, cohort_id: input.cohort_id } }).then((res) => {
    return Array.from(new Set(res));
  })
  let output = result[0]
  for (let i = 0; i < output.length; i++) {
    if (output[i].test_type == 'meeting') {
      let test_id = output[i].test_id
      const all_live = await AllLiveEvent.findAll({
        where: {
          live_event_id: test_id,
          status: 0
        }
      });
      if (all_live.length > 0) {
        output[i]['end_time'] = all_live[0].end_time
        output[i]['start_time'] = all_live[0].start_time
        output[i]['meeting_time_zone'] = all_live[0].time_zone
      } else {
        const live_event = await LiveEvents.findAll({
          where: {
            id: test_id,
            status: 0
          }
        });
        if (live_event.length > 0) {
          output[i]['end_time'] = live_event[0].end_time
          output[i]['start_time'] = live_event[0].start_time
          output[i]['meeting_time_zone'] = live_event[0].time_zone
        }
      }
    }
  }
  res.status(200).send(API._200(await output));
};

exports.save_setting = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const data = await db_helper.selectByWhere("NotificationSetting", { 'user_id': input.user_id })
  await db_helper.query("update users set overdue_notification=" + input.oberdue + " where id =" + input.user_id)
  if (data.length > 0) {
    input["id"] = data[0].id;
    res.status(200).send(API._200(await db_helper.update("NotificationSetting", input)));
  } else {
    res.status(200).send(API._200(await db_helper.addData("NotificationSetting", input)));
  }
};
exports.add_certificate = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  let certificate = await db_helper.addData("Certificate", input);
  let cohortres = {
    certi_id: certificate.id,
    cohort_name: input.certificate_name,
    cource_id: 1,
    course_type: "Free",
    method_id: 0,
    userslist: "",
    knowassessments: "",
    practicetests: "",
    ketexamtests: "",
    email_templates: "",
    videos: "",
    mindmaps: "",
    live_events: ""
  }
  let coh = await db_helper.addData("Cohort", cohortres);
  let self = {
    cohort_id: coh.id,
    certi_id: certificate.id,
    class_name: input.certificate_name,
    publish_free_trial: 0
  }
  await db_helper.addData("SelfPaced", self);
  res.status(200).send(API._200(await certificate));
};
exports.all_failed_emails = async (req, res) => {
  const _emails = await FailedEmail.findAll({
    where: {
      mail_success: 0,
      status: 0
    },
    order: [
      ['id', 'DESC'],
    ]
  });
  res.status(200).send(API._200(await _emails));
};
exports.all_success_emails = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const _emails = await FailedEmail.findAll({
    where: {
      mail_success: 1,
      status: 0
    },
    order: [
      ['id', 'DESC'],
    ]
  });
  res.status(200).send(API._200(await _emails));
};
exports.delete = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const result = await db.sequelize.query("delete from notifications where cohort_id= :cohort_id and test_id= :test_id and test_type='" + input.test_type + "'", { replacements: { test_id: input.test_id, cohort_id: input.cohort_id } }).then((res) => {
    return Array.from(new Set(res));
  })
  res.status(200).send(API._200(await result));
};
exports.delete_failed_emails = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  res.status(200).send(API._200(await db_helper.statusChange('FailedEmail', input.id)));
};
exports.update_certificate = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  let domain_sequence = input.domain_sequence;
  await db_helper.query("UPDATE cohorts set domain_sequence='" + domain_sequence + "' WHERE status=0 AND certi_id=" + input.id);
  input.domain_sequence = input.domain_sequence.toString();
  res.status(200).send(API._200(await db_helper.update('Certificate', input)));
};
exports.alluserforcohortadd = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const Op = db.Sequelize.Op;
  let companies = [];
  if (input.company_id == 0) {
    companies = await db.sequelize.query("select GROUP_CONCAT(id) id from companies where status=0")
      .then(function (data) {
        return Array.from(new Set(data[0]));
      })
  } else {
    companies.push({ id: input.company_id });
  }

  var user = await User.findAndCountAll({
    where: {
      roll_id: 3,
      status: 0,
      company_id: {
        [Op.in]: companies[0].id ? companies[0].id.split(",") : 0
      },
      [Op.or]: [{
        email: {
          [Op.like]: '%' + input.search + '%'
        }
      },
      {
        name: {
          [Op.like]: '%' + input.search + '%'
        }
      }
      ]
    },
    limit: [((input.page - 1) * input.limit), input.limit],
  })
  for (let i = 0; i < user.rows.length; i++) {
    var all = await db_helper.query(`select id from login_logs where user_id=${user.rows[i].id} and status=0`);
    user.rows[i].notes = all[0].length > 0 ? true : false;
  }
  res.status(200).send(API._200(await user));
};