import moment from "moment";

const MAX_YEARS = 121;
const MAX_DAYS_IN_MONTH = 31;
export const FEBRUARY_MONTH_FORMAT = '2';

type FabDateTypes = {
    29: boolean;
    30: boolean;
    31: boolean
}

const lastDays: FabDateTypes = {
    '29': true,
    '30': true,
    '31': true
}

const getDays = (days: number = MAX_DAYS_IN_MONTH) => {
    return new Array(days).fill(true).map((_, i: number) => ({
        value: i+1,
        displayValue: i+1
    }))
};

const getMonths = () => moment.months().map((month: string, i) => ({
    value: i + 1,
    displayValue: month
}));

const getYears = () => {
    const year = moment().year() - 1;

    return new Array(MAX_YEARS).fill(true).reduce((arr, _, i: number) => {
        const value = year - i;

        arr.push({
            value,
            displayValue: value
        });

        return arr;
    }, []);
}

export const getDefaultDataConfig = () => ( {
    months: getMonths(),
    years: getYears(),
    defaultDays: getDays()
})

export const getDaysInMonth = (month: string, year?: number | string) =>
    !year
        ? getDays(moment(month).daysInMonth())
        : getDays(moment(`${year}-${month}`, 'YYYY-MM').daysInMonth())

export const getCorrectFebruaryDay = (day: number | string, year?: number | string) => {
    // @ts-ignore
    const fabDay = lastDays[day] ? getDaysInMonth(FEBRUARY_MONTH_FORMAT, year).length : day;

    return { value: fabDay, displayValue: fabDay }
}

export const parseTimestemp = (timestemp: number) => {
    const [m, d, y] = moment.unix(timestemp).format("L").split('/');

    return {
        day: Number(d).toString(),
        month: Number(m).toString(),
        year: Number(y).toString()
    }
}

export const parseToTimestemp = (date: string) => moment(date).format('x');

export const parseTimestempHours = (timestemp: number) => {
    const [, hours, time] = moment(timestemp)
        .format('MM/DD/YYYY hh:mm A')
        .split(' ');

    return {
        hours: hours && Number(hours.split(':')[0]).toString(),
        minutes: hours && Number(hours.split(':')[1]).toString(),
        time
    }
};

export const paresHoursToTimestempWithDate = ({ dateOfBirth, hours, minutes, time }: any) =>
    moment(`${moment(dateOfBirth).format('L')} ${hours}:${minutes} ${time}`, "MM/DD/YYYY HH:mm A").format('x');

export const parseHoursToTimestemp = ({ hours, minutes, time }: any) => moment(`${hours}:${minutes} ${time}`, 'HH:mm A').format('x')

