import { Timestamp } from "components/TimezoneSelect/utilities/timestamp";
import { Schedule } from "types/campaigns";
import { ScheduleForm } from "./types";
import momentTz from "moment-timezone";

export function mapToScheduleForm(schedule: Schedule): ScheduleForm {
  const timezone = schedule.timezone ?? momentTz.tz.guess();

  const start = schedule.startTimestamp
    ? Timestamp.timestampToPlainParts({
        timestamp: schedule.startTimestamp,
        timezoneName: timezone,
      })
    : null;
  const end = schedule.endTimestamp
    ? Timestamp.timestampToPlainParts({
        timestamp: schedule.endTimestamp,
        timezoneName: timezone,
      })
    : null;

  return {
    sendType: schedule.sendType,
    startPlainDate: start?.plaindate ?? null,
    startPlainTime: start?.plaintime ?? null,
    endPlainDate: end?.plaindate ?? null,
    endPlainTime: end?.plaintime ?? null,
    timezone: timezone,
  };
}

export function mapToSchedule(scheduleForm: ScheduleForm): Schedule {
  const { startPlainDate, startPlainTime, timezone } = scheduleForm;
  const startTimestamp =
    startPlainDate && startPlainTime && timezone
      ? Timestamp.plainPartsToTimestamp({
          plaindate: startPlainDate,
          plaintime: startPlainTime,
          timezoneName: timezone,
        }).timestamp
      : null;
  const { endPlainDate, endPlainTime } = scheduleForm;
  const endTimestamp =
    endPlainDate && endPlainTime && timezone
      ? Timestamp.plainPartsToTimestamp({
          plaindate: endPlainDate,
          plaintime: endPlainTime,
          timezoneName: timezone,
        }).timestamp
      : null;

  return {
    startTimestamp: startTimestamp,
    endTimestamp: endTimestamp,
    sendType: scheduleForm.sendType,
    timezone: timezone,
  };
}
