import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { DATE_FORMAT } from '@shared/helpers';
import { isToday, isTomorrow } from '@utils/date';
import * as moment from 'moment';

@Injectable({
    providedIn: 'root',
})
export class DateTransformerService {
    private readonly DATE_FORMAT = 'DD.MM.YYYY';
    private readonly TIME_PREFIXED_DATE_FORMAT = 'HH:mm DD.MM.YYYY';
    constructor(private translate: TranslateService) {}

    toString(date?: Date): string {
        if (!date) {
            return '';
        }

        if (isToday(date)) {
            return this.translate.instant('SHARED.TODAY');
        }

        if (isTomorrow(date)) {
            return this.translate.instant('SHARED.TOMORROW');
        }

        return this.formatDate(date);
    }

    toDateString(date?: Date | string, withTimePrefix = false) {
        if (!date) {
            return '';
        }

        return this.formatDate(date, withTimePrefix);
    }

    toLocalDateString(date?: Date | string): string {
        if (!date) {
            return '';
        }

        return moment.parseZone(date).local(true).format(DATE_FORMAT);
    }

    private formatDate(date: Date | string, withTimePrefix = false) {
        return withTimePrefix
            ? moment(date).format(this.TIME_PREFIXED_DATE_FORMAT)
            : moment(date).format(this.DATE_FORMAT);
    }
}
