import { FoodTracking } from "../model/foodTracking";
import mongoose from "mongoose";

export enum MealOptions {
  MORGENESSEN = "zmorge",
  ZNUENI = "znueni",
  ZMITTAG = "zmittag",
  ZVIERI = "zvieri",
  ZNACHT = "znacht",
}

export class TrackingController {
  async handleGetTracking(req, res) {
    const date = new Date(req.query.date);

    await FoodTracking.find({
      username: req.user.username,
      date: new Date(date),
    })
      .populate("fooditem")
      .exec((err, result) => {
        let mealMap = new Map();

        for (const option in MealOptions) {
          mealMap.set(MealOptions[option], new Array());
        }

        if (result) {
          result.forEach((entry) => {
            mealMap.get(entry.mealOption).push(entry);
          });
        }

        const convertToArray = (mealMap) => {
          let mealArray = new Array();
          mealMap.forEach((value, key) => {
            mealArray.push({
              name: key,
              items: value,
            });
          });

          return mealArray;
        };

        res.json(convertToArray(mealMap));
      });
  }

  async handlePostFoodTracking(req, res) {
    const username = req.user.username;
    const fooditem: mongoose.Schema.Types.ObjectId = req.body.fooditem;
    const date = new Date(req.body.date);

    const mealOption = req.body.mealOption;
    const amount = req.body.amount;
    new FoodTracking({
      username,
      fooditem,
      date,
      mealOption,
      amount,
    }).save((err, result) => {
      if (err) {
        return res.sendStatus(500);
      }
      res.json(result);
    });
  }

  async handleRemoveFoodTracking(req, res) {
    const _id = req.body._id;
    const username = req.user.username;

    const count = await FoodTracking.deleteOne(
      { _id, username },
      null,
      (err) => {
        if (err) {
          return res.sendStatus(500);
        }
      }
    );

    if (count.ok === 0) {
      res.sendStatus(403);
    } else {
      res.sendStatus(202);
    }
  }
}

export const trackingController = new TrackingController();
