const bcrypt = require("bcryptjs");
const _ = require("lodash");
const express = require("express");
const { TestResult } = require("../../models/TestResult");
const router = express.Router();

module.exports.add = async (req, res) => {
  try {
    let record = req.body;
    user = new TestResult(record);
    user.user = req.user._id;
    user = await user.save();
    return res.status(200).send(user);
  } catch (err) {
    console.error(err);
    return res.status(400).send({ error: err.message });
  }
};

module.exports.getSingle = async (req, res) => {
  try {
    const record = await TestResult.findById(req.params.id);
    if (!record) throw Error("The record with the given ID was not found.");
    return res.send(record);
  } catch (err) {
    console.error(err);
    return res.status(404).send({ error: err.message });
  }
};

module.exports.delete = async (req, res) => {
  try {
    const record = await TestResult.findByIdAndRemove(req.params.id);
    if (!record) throw Error("The record with the given ID was not found.");
    return res.send(record);
  } catch (err) {
    console.error(err);
    return res.status(404).send({ error: err.message });
  }
};

module.exports.update = async (req, res) => {
  try {
    let record = await TestResult.findById(req.params.id);
    if (!record) throw Error("The record with the given ID was not found.");

    record = await TestResult.findByIdAndUpdate(req.params.id, req.body);
    res.send(record);
  } catch (err) {
    console.error(err);
    return res.status(400).send({ error: err.message });
  }
};

module.exports.all = async (req, res) => {
  try {
    let drivers = await TestResult.find({ user: req.user._id });
    return res.status(200).send(drivers);
  } catch (err) {
    console.log(err);
    return res.status(400).send({ error: err.message });
  }
};

module.exports.query = async (req, res) => {
  try {
    let query = req.body.query;
    query = query ? query : {};
    query.page = query.page ? query.page : 0;
    query.pageSize = query.pageSize ? query.pageSize : 10;
    let conditions = {};
    if (query.search) {
      conditions.$and = [
        {
          $or: [{ name: { $regex: new RegExp(query.search, "i") } }],
        },
      ];
    }
    let skip = query.page * query.pageSize;
    let sort = {};
    if (query.orderBy) {
      sort[query.orderBy.field] = query.orderDirection == "asc" ? 1 : -1;
    }
    const records = await TestResult.find(conditions)
      .skip(skip)
      .sort(sort)
      .limit(query.pageSize);

    let total = await TestResult.countDocuments(conditions);
    // total = Math.ceil(total / query.pageSize);
    res.send({ data: records, page: query.page, total });
  } catch (err) {
    console.error(err);
    return res.status(400).send({ error: err.message });
  }
};
