const { splitSite } = require("../middlewares");
const db = require("../models");
const CalendarEvent = db.calendar_event;
const moment = require("moment-timezone");

// Create a new Event
exports.createCalendarEvent = (req, res) => {
  // Validate request
  if (!req.body.start_time) {
    res.status(400).send({ message: "Content can not be empty!" });
    return;
  }
  const site = splitSite.findSiteNumber(req);
	// Create an Event
  const calendarEvent = new CalendarEvent({
    title: req.body.title,
		type: req.body.type,
		description: req.body.description,
		department: req.body.department,
		notes: req.body.notes,
		start_time: req.body.start_time,
		stop_time: req.body.stop_time,
		source_type: req.body.source_type,
		source_uuid: req.body.source_uuid,
		source_name: req.body.source_name,
		target_type: req.body.target_type,
		target_uuid: req.body.target_uuid,
		target_name: req.body.target_name,
		link_event_uuid: req.body.link_event_uuid,
		link_event_name: req.body.link_event_name,
		data: req.body.data,
    color: req.body.color,
    confirmed: req.body.confirmed || false,
		files: req.body.files,
		status: req.body.status || 'active',
		signup_start_date: req.body.signup_start_date,
		member_col: req.body.member_col,
    new_patient: req.body.new_patient,
		tags: req.body.tags,
		create_by: req.body.create_by,
		create_date: req.body.create_date,
		edit_by: req.body.create_by,
		edit_date: req.body.create_date,
		youtube_video_id: req.body.youtube_video_id,
		edit_history: req.body.edit_history,
    site,
    event_location: req.body.event_location,
    event_prediction_date: req.body.event_prediction_date,
    event_reminder_type: req.body.event_reminder_type,
    rrule: req.body.rrule,
    meal_type: req.body.meal_type,
    activity_category: req.body.activity_category,
    ingredients: req.body.ingredients
  });
  // Save event in the database
  calendarEvent
    .save(calendarEvent)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while creating the Calendar Event."
      });
    });
};

// Retrive all events from database.
exports.getAllEvents = (req, res) => {
	var params = req.query;
	var condition = {};
	if (params.date) {
		condition['start_time'] = {
			$gte: moment(params.date + ' 00:00:00:000').toDate(),
			$lt: moment(params.date + ' 23:59:59.999').toDate()
		};
	}
	if (params.from && params.to) {
		condition['start_time'] = {
      $gte: moment(params.from + ' 00:00:00.000').toDate(),
      $lt: moment(params.to+ ' 23:59:59.999').toDate()
    };
	}
	if (params.start_date && params.end_date) {
		// for FullCalendar, if has start_date and end_date, format: YYYY-MM-DD
		// FullCalendar gives start_date and end_date, end_date is day+1 of current view
		condition['start_time'] = {
			$gte: moment(parameter.start_date + 'T00:00:00:00', "America/New_York").toDate()
		};
		condition['stop_time'] = {
			$lt: moment(parameter.end_date + 'T00:00:00:00', "America/New_York").toDate()
		};
	}
  if (params.type) {
    condition['type'] = params.type;
  }
	condition = splitSite.splitSiteGet(req, condition);
	CalendarEvent.find(condition)
		.then(data => {
			res.send(data);
		})
		.catch(err => {
			res.status(500).send({
				message:
					err.message || "Some error occurred while retrieving Events."
			});
		});
};

exports.getEventsByCustomer = (req, res) => {
  var params = req.query;
  const name_cn = params.namecn || '';
  const name = params.name;
  const id = params.id;
  if (id && name) {
    var ObjectId = require('mongoose').Types.ObjectId;
    var objId = new ObjectId(id);
    const regex = new RegExp(name_cn, 'i') // i for case insensitive
    CalendarEvent.find( { $or:[ { data: {'customer':objId}}, {data: {'customer':id}}, {'target_name': name }, {'target_name': {$regex: regex}} ]}).then(data => {
			res.send(data);
		})
		.catch(err => {
			res.status(500).send({
				message:
					err.message || "Some error occurred while retrieving Events for customers."
			});
		});
  } else {
    res.send({data: []});
  }
};

// Get One Event by Id
exports.getEvent = (req, res) => {
  const id = req.params.id;
  CalendarEvent.findById(id)
    .then(data => {
      if (!data)
        res.status(404).send({ message: "Not found Event with id " + id });
      else res.send(data);
    })
    .catch(err => {
      res
        .status(500)
        .send({ message: "Error retrieving Event with id=" + id });
    });
};

// Update a Event by the id in the request
exports.updateEvent = (req, res) => {
  if (!req.body) {
    return res.status(400).send({
      message: "Data to update can not be empty!"
    });
  }
  const id = req.params.id;
  CalendarEvent.findByIdAndUpdate(id, req.body, { useFindAndModify: false })
    .then(data => {
      if (!data) {
        res.status(404).send({
          message: `Cannot update Event with id=${id}. Maybe Event was not found!`
        });
      } else res.send({ success: true, message: "Event was updated successfully." });
    })
    .catch(err => {
      res.status(500).send({
        success: false,
        message: "Error updating Event with id=" + id
      });
    });
};

// assign driver to the transportation Event 
exports.assignTransportationToEvents = (req, res) => {
	var ids = req.body.eventIds || [];
	var transportationId = req.body.transportationId;
	var transportationName = req.body.transportationName;
	// ids.forEach(id => {
	// 	CalendarEvent.findByIdAndUpdate(id, {link_event_uuid: transportationId,
	// 		link_event_name: transportationName}, { useFindAndModify: false })
  //   .then(data => {
  //     if (!data) {
  //       res.status(404).send({
  //         message: `Cannot update Event with id=${id}. Maybe Event was not found!`
  //       });
  //     } else res.send({ success: true, message: "Event was updated successfully." });
  //   })
  //   .catch(err => {
  //     res.status(500).send({
  //       success: false,
  //       message: "Error updating Event with id=" + id
  //     });
  //   });
	// })
  Promise.all(ids.map((id) => CalendarEvent.findByIdAndUpdate(id, {link_event_uuid: transportationId,
    link_event_name: transportationName}, { useFindAndModify: false }))).then((data) => {
      if (data) {
        res.send({ success: true, message: "Event was updated successfully." });
      }
    });
}


// Disable an Event by the id in the request
exports.disableEvent = (req, res) => {
  const id = req.params.id;
  CalendarEvent.findByIdAndUpdate(id, { ...req.body, status: 'inactive'}, { useFindAndModify: false })
    .then(data => {
      if (!data) {
        res.status(404).send({
          message: `Cannot update Event with id=${id}. Maybe Event was not found!`
        });
      } else res.send({ success: true, message: "Event was updated successfully." });
    })
    .catch(err => {
      res.status(500).send({
        success: false,
        message: "Error updating Event with id=" + id
      });
    });
};

// Delete a Event by id
exports.deleteEvent= (req, res) => {
  const id = req.params.id;
  CalendarEvent.findByIdAndRemove(id)
    .then(data => {
      if (!data) {
        res.status(404).send({
          message: `Cannot delete Event with id=${id}. Maybe Event was not found!`
        });
      } else {
        res.send({
          message: "Event was deleted successfully!"
        });
      }
    })
    .catch(err => {
      res.status(500).send({
        message: "Could not delete Event with id=" + id
      });
    });
};