import dotenv from 'dotenv';
import mongoose from 'mongoose';
import { jobModel } from '../../database/schemas/production/job.schema.js';
import log4js from 'log4js';
import {
  deleteObject,
  getObject,
  listObjects,
  listObjectsByProperties,
  newObject,
  getModelStats,
  getModelHistory,
} from '../../database/database.js';
import { subJobModel } from '../../database/schemas/production/subjob.schema.js';
dotenv.config();

const logger = log4js.getLogger('Jobs');
logger.level = process.env.LOG_LEVEL;

export const listJobsRouteHandler = async (
  req,
  res,
  page = 1,
  limit = 25,
  property = '',
  filter = {},
  search = '',
  sort = '',
  order = 'ascend'
) => {
  const result = await listObjects({
    model: jobModel,
    page,
    limit,
    property,
    filter,
    search,
    sort,
    order,
    populate: ['gcodeFile'],
  });

  if (result?.error) {
    logger.error('Error listing jobs.');
    res.status(result.code).send(result);
    return;
  }

  logger.debug(`List of jobs (Page ${page}, Limit ${limit}). Count: ${result.length}`);
  res.send(result);
};

export const listJobsByPropertiesRouteHandler = async (
  req,
  res,
  properties = '',
  filter = {},
  masterFilter = {}
) => {
  const result = await listObjectsByProperties({
    model: jobModel,
    properties,
    filter,
    masterFilter,
  });

  if (result?.error) {
    logger.error('Error listing jobs.');
    res.status(result.code).send(result);
    return;
  }

  logger.debug(`List of jobs. Count: ${result.length}`);
  res.send(result);
};

export const getJobRouteHandler = async (req, res) => {
  const id = req.params.id;
  const result = await getObject({
    model: jobModel,
    id,
    populate: ['gcodeFile', 'printers'],
  });
  if (result?.error) {
    logger.warn(`Job not found with supplied id.`);
    return res.status(result.code).send(result);
  }
  logger.debug(`Retreived job with ID: ${id}`);
  res.send(result);
};

export const newJobRouteHandler = async (req, res) => {
  const newData = {
    createdAt: new Date(),
    updatedAt: new Date(),
    quantity: req.body.quantity,
    printers: req.body.printers,
    gcodeFile: req.body.gcodeFile,
    state: { type: 'draft' },
  };
  const result = await newObject({
    model: jobModel,
    newData,
    user: req.user,
  });
  if (result.error) {
    logger.error('No job created:', result.error);
    return res.status(result.code).send(result);
  }

  logger.debug(`New job with ID: ${result._id}`);

  var printerCount = 0;

  for (let i = 0; i < newData.quantity; i++) {
    const newSubJobData = {
      createdAt: new Date(),
      updatedAt: new Date(),
      printer: newData.printers[printerCount],
      gcodeFile: req.body.gcodeFile,
      number: i + 1,
      job: result._id,
      state: { type: 'draft' },
    };
    const subJobResult = await newObject({
      model: subJobModel,
      newData: newSubJobData,
      user: req.user,
    });
    if (subJobResult.error) {
      logger.error('No sub job created:', result.error);
      return res.status(result.code).send(result);
    }
    if (printerCount >= newData.printers.length - 1) {
      printerCount = 0;
    } else {
      printerCount += 1;
    }
  }

  res.send(result);
};

export const deleteJobRouteHandler = async (req, res) => {
  // Get ID from params
  const id = new mongoose.Types.ObjectId(req.params.id);

  logger.trace(`Job with ID: ${id}`);

  const result = await deleteObject({
    model: jobModel,
    id,
    user: req.user,
  });
  if (result.error) {
    logger.error('No job deleted:', result.error);
    return res.status(result.code).send(result);
  }

  logger.debug(`Deleted job with ID: ${result._id}`);

  res.send(result);
};

export const getJobStatsRouteHandler = async (req, res) => {
  console.log('Getting job stats');
  const result = await getModelStats({ model: jobModel });
  if (result?.error) {
    logger.error('Error fetching job stats:', result.error);
    return res.status(result.code).send(result);
  }
  logger.trace('Job stats:', result);
  res.send(result);
};

export const getJobHistoryRouteHandler = async (req, res) => {
  const from = req.query.from;
  const to = req.query.to;
  const result = await getModelHistory({ model: jobModel, from, to });
  if (result?.error) {
    logger.error('Error fetching job history:', result.error);
    return res.status(result.code).send(result);
  }
  logger.trace('Job history:', result);
  res.send(result);
};
