/* eslint-disable no-underscore-dangle */
import moment from 'moment-timezone';
const CalendarUtils = {
  // default timezone is İstanbul
  timeZone: 'Europe/Istanbul',
  // default language is English
  locale: 'tr',
  timeFormat: '24-hour',
  setLocale(locale) {
    moment.locale(locale);
    CalendarUtils.locale = locale;
  },
  setTimeZone(timeZone) {
    // hack for Turkey time zone problem
    if (timeZone === 'Europe/Istanbul') {
      CalendarUtils.timeZone = 'Europe/Moscow';
    }
    else {
      CalendarUtils.timeZone = timeZone;
    }
  },
  setTimeFormat(timeFormat) {
    CalendarUtils.timeFormat = timeFormat;
  },
  fixHourDifference(date) {
    const browserOffset = new Date().getTimezoneOffset();
    const timeZoneOffset = moment.tz.zone(CalendarUtils.timeZone).offset(new Date());
    const diff = (browserOffset - timeZoneOffset) / 60;
    date.setHours(date.getHours() - diff);
    return date;
  },
  format(date, formatString) {
    if (formatString === 'HH:mm' && CalendarUtils.timeFormat === '12-hour') {
      return moment(date).tz(CalendarUtils.timeZone).format('hh:mm A');
    }
    return moment(date).tz(CalendarUtils.timeZone).format(formatString);
  },
  /**
   * Return startDate and endDate Unix time stamp values from the date objects in parameters.
   *
   * @param date (JS date object) of the selected day.
   * @param startTime (JS date object) of the start hour.
   * @param endTime (JS date object) of the end hour.
   * @returns {{startDate: number, endDate: number}}
   */
  getStartAndEndDateFromInputs(date, startTime, endTime) {
    let startDate = new Date(date.getTime());
    startDate.setHours(startTime.getHours(), startTime.getMinutes(), 0);
    let endDate = new Date(date.getTime());
    endDate.setHours(endTime.getHours(), endTime.getMinutes(), 0);
    startDate = CalendarUtils.fixHourDifference(startDate);
    endDate = CalendarUtils.fixHourDifference(endDate);
    // convert dates to unix time
    return {
      startDate: startDate.getTime() / 1000,
      endDate: endDate.getTime() / 1000,
    };
  },
  elapsedTime(date) {
    return moment(date).tz(CalendarUtils.timeZone).fromNow();
  },
  elapsedTimeBetweenDates(date1, date2) {
    return moment(date1).from(moment(date2));
  },
  getMonday() {
    return moment().startOf('isoWeek').toDate();
  },
  getStartEndOfWeek(relativeWeekNumber = 0) {
    // const relativeDate = new Date();
    // relativeDate.setDate(relativeDate.getDate() + (relativeWeekNumber * 7));
    const addition = relativeWeekNumber * (7 * 24 * 60 * 60 * 1000);
    const monday = new Date(new Date(CalendarUtils.getMonday()).getTime() + addition);
    monday.setHours(0, 0, 0, 0);
    const sunday = new Date(monday.getTime());
    sunday.setDate(monday.getDate() + 6);
    sunday.setHours(23, 59, 59, 99);
    return { relativeWeekNumber, firstDayOfWeek: monday, lastDayOfWeek: sunday };
  },
};
export default CalendarUtils;
