import { Component, OnChanges, OnInit } from '@angular/core';
import { getSunday, getStartOfTheWeek } from '@utils/date';
import { DateSelectorBaseComponent } from '../date-selector-base';
import { IDateTab } from '@toolkit/date-tabs/date-tabs.component';
import { DatesTranslationService } from '@shared/services/dates-translation.service';
import * as moment from 'moment';

export type IWeekTabValue = {
    dateFrom: Date;
    dateTo: Date;
};

@Component({
    selector: 'week-tabs',
    templateUrl: './week-tabs.component.html',
})
export class WeekTabsComponent
    extends DateSelectorBaseComponent<IWeekTabValue>
    implements OnChanges, OnInit {

    ngOnInit() {
        super.ngOnInit();
    }

    constructor(protected translationService: DatesTranslationService) {
        super(translationService);
    }

    protected updateTabs() {
        this.tabs = this.tabs.map((tab) => {
            const sunday = tab.value.dateTo;
            const monday = tab.value.dateFrom;
            const isTabActive = this.isActive(monday);
            const isTabDisabled = !this.isEnabled(monday, sunday);

            return {
                ...tab,
                active: isTabActive,
                disabled: isTabDisabled,
            };
        });
    }
    protected computeNextDate(date: Date): Date {
        return moment(date).add(1, 'week').toDate();
    }

    protected computeFirstDate(): Date {
        return getStartOfTheWeek(this.dateFrom);
    }

    protected generateTab(monday: Date): IDateTab<IWeekTabValue> {
        const isTabActive = this.isActive(monday);
        const sunday = getSunday(monday);
        const isTabDisabled = !this.isEnabled(monday, sunday);

        return {
            label: this.getTabLabel(monday, sunday),
            mobileLabel: this.getTabMobileLabel(monday, sunday),
            value: {
                dateFrom: monday,
                dateTo: sunday,
            },
            active: isTabActive,
            disabled: isTabDisabled,
        };
    }

    private getTabLabel(monday: Date, sunday: Date) {
        const mondayShortDateString =
            this.translationService.getShortDateString(monday);

        const sundayShortDateString =
            this.translationService.getShortDateString(sunday);

        return `${mondayShortDateString} - ${sundayShortDateString}`;
    }

    private getTabMobileLabel(monday: Date, sunday: Date) {
        const mondayFullDateString =
            this.translationService.getFullDateString(monday);

        const sundayFullDateString =
            this.translationService.getFullDateString(sunday);

        return `${mondayFullDateString} - ${sundayFullDateString}`;
    }

    private isEnabled(monday: Date, sunday: Date) {
        return (
            moment(monday).isSameOrAfter(this.minDate) &&
            moment(sunday).isSameOrBefore(this.maxDate)
        );
    }
}
