import moment from "moment-timezone";
import optional from "./global/optional";

const settings = window.settings || {};

moment.locale(window.appLanguage)

export const localTimeZone = moment.tz.guess();

export const serverDateTimeFormat = 'YYYY-MM-DD H:mm:ss';

export const serverDateFormat = 'YYYY-MM-DD';

export const serverTimeFormat = 'H:mm:ss';

export const date_format = () => {
    return {
        'd-m-Y': 'DD-MM-YYYY',
        'm-d-Y': 'MM-DD-YYYY',
        'Y-m-d': 'YYYY-MM-DD',
        'm/d/Y': 'MM/DD/YYYY',
        'd/m/Y': 'DD/MM/YYYY',
        'Y/m/d': 'YYYY/MM/DD',
        'm.d.Y': 'MM.DD.YYYY',
        'd.m.Y': 'DD.MM.YYYY',
        'Y.m.d': 'YYYY.MM.DD',
    };
};

export const formatted_date = () => {
    return date_format()[optional(settings, 'date_format')] || date_format()['d-m-Y'];
};

export const time_format = () => {
    const format = optional(settings, 'time_format');

    const time_format = settings.time_format || 'H'

    return format === 'h' ? `${settings.time_format}:mm A` : `${time_format}:mm`;
}

export const formatted_time = () => {
    return optional(settings, 'time_format') === 'h' ? '12' : '24';
}

export const getDateFromNow = (date, format) => {
    return moment(date).calendar({
        sameDay: '[Today]',
        nextDay: '[Tomorrow]',
        nextWeek: 'dddd',
        lastDay: '[Yesterday]',
        lastWeek: '[Last] dddd',
        sameElse: format
    });
}

export const isValidDate = string => {
    if (!string)
        return false;

    if (typeof parseInt(string) === 'number' && string.split('-').length <= 1)
        return false;

    return !isNaN(new Date().getTime());
}

export const localToUtc = (time = null) => {
    if (!time) {
        return '';
    }

    moment.locale('en');
    return moment(time, time_format()).utc().format('HH:mm')
}

export const formatDateForServer = (date = null) => {
    if (!date) {
        return '';
    }

    moment.locale('en');
    return moment(moment(date), formatted_date()).format(serverDateFormat);
}

export const formatTimeForServer = (time = null) => {
    if (!time) {
        return '';
    }

    moment.locale('en');
    return moment(time, time_format()).format(serverTimeFormat);
}

export const formatDateTimeForServer = (dateTime = null) => {
    if (!dateTime) {
        return '';
    }
    return moment(dateTime, `${formatted_date()} ${time_format()}`).utc().format(serverDateTimeFormat)
}

export const formatUtcToLocal = (time = null, format = false) => {
    if (!time)
        return null;

    return moment.utc(time, serverTimeFormat).local().format(format || time_format());
}

export const formatDateToLocal = (date, withTime = false) => {
    if (!date)
        return '';
    const formatString = withTime ? `${formatted_date()} ${time_format()}` : formatted_date();

    return moment.utc(date, withTime ? serverDateTimeFormat : serverDateFormat)
        .local()
        .format(formatString);
};

export const dateTimeToLocalWithFormat = (date = null) => {
    if (!date) {
        return '';
    }

    const formatString = `${formatted_date()} ${time_format()}`;

    return moment.utc(date, serverDateTimeFormat)
        .local()
        .format(formatString);
}

export  const getTimeFromDateTime = (dateTime, timeFormat) =>{
    timeFormat = timeFormat == 12 ? 'h:mm a' : 'HH:mm';
    return moment(dateTime).format(timeFormat);
}

export const getUtcToLocalTimeOnly = (value) => {
    return moment.utc(value, serverDateTimeFormat)
        .local()
        .format(serverTimeFormat);
}

export const timeInterval = (date) => {
    return moment(date).utc(false).fromNow();
};

export const differentInTime = (startTime, endTime, withDate = false) => {
    if (withDate) {
        return moment.duration(moment(endTime, serverDateTimeFormat).diff(moment(startTime, serverDateTimeFormat)));
    }

    if (moment(endTime, serverTimeFormat).diff(moment(startTime, serverTimeFormat), 'hours') < 0) {
        startTime = moment(`${today().format(serverDateFormat)} ${startTime}`);
        endTime = moment(`${today().add(1, 'day').format(serverDateFormat)} ${endTime}`)
    }

    return moment.duration(moment(endTime, serverTimeFormat).diff(moment(startTime, serverTimeFormat)));
}

export const getDifferentTillNow = (startTime, endTime = moment.now()) => {
    return differentInTime(dateTimeToLocalWithFormat(startTime), moment(endTime).format(serverDateTimeFormat), true);
}

export const convertSecondToHourMinutes = (seconds) => {
    const min = parseInt(parseInt(seconds) / 60);
    const hour = min / 60;
    const absHour = parseInt(hour);
    const absMin = Math.abs(min - (absHour * 60));

    let timeFormat = `${String(absHour).length === 1 ? `0${absHour}` : absHour}:${String(absMin).length === 1 ? `0${absMin}` : String(absMin).substr(0, 2)}`;

    return (absHour === 0 && (min - (absHour * 60)) < 0) ? `-${timeFormat}` : timeFormat;
}

export const isAfterNow = (value) => {
    return moment(value, serverDateFormat).isAfter(moment.now());
}

export const getHoursAndMinutesInString = (seconds, short = false, roundedTo = 'abs') => {
    let min = Math.abs(parseInt(seconds) / 60);

    if (roundedTo === 'ceil') {
        min = Math.ceil(parseInt(seconds) / 60);
    }

    const hour = min / 60;
    const absHour = parseInt(hour);
    const absMin = Math.abs(min - (absHour * 60));
    let H = 'hours'
    let h = 'hour'
    let M = 'minutes'
    let m = 'minute'
    if (short) {
        h = 'h';
        H = 'h';
        m = 'm';
        M = 'm';
    }
    if (absHour > 0) {
        return `${absHour} ${absHour > 1 ? H : h} 
        ${absMin > 0 ? `and ${String(absMin).substr(0, 2)} ${absMin > 1 ? M : m}` : ''}`;
    }
    return `${String(absMin).substr(0, 2)} ${absMin > 1 ? M : m}`;
}

export const timeToDateTime = (date, time) => {
    return moment(`${moment(date, serverDateFormat).format(serverDateFormat)} ${time}`);
}

export const onlyTime = date => {
    return moment.utc(date, serverDateTimeFormat)
        .local()
        .format(time_format());
};

export const startAndEndOf = (year, month) => {
    return [
        moment([year, month]).startOf('month'),
        moment([year, month]).endOf('month')
    ]
}

export const dateTimeFormat = (value) => {
    if (value) {
        return `${onlyTime(value)}, ${calenderTime(value, false)}`
    }
    return null;
};

export const calenderTimeWithMonthSortName = (date) => {
    return moment(date).format('DD MMM, YY')
}
