import { LanguageModel } from "@insite/client-framework/Types/ApiModels";

interface Props {
    dateTime: Date;
    options?: Intl.DateTimeFormatOptions;
    language?: LanguageModel | null;
    ignoreOffset?: boolean;
}

/**
 * This component will return a dateTime localized to the language of the session.
 * This component should only be used in cases where the dateTime cannot be generated server side.
 */
const getLocalizedDateTime = ({ dateTime, language, options, ignoreOffset }: Props) => {
    const locale = language?.cultureCode || language?.languageCode;

    const getDisplayValue = (value: Date, locale?: string) => {
        if (ignoreOffset) {
            const timeDiff = value.getTimezoneOffset() * 60000;
            const adjustedDate = new Date(value.valueOf() + timeDiff);
            return adjustedDate.toLocaleDateString(locale, options);
        }
        return value.toLocaleDateString(locale, options);
    };

    try {
        return getDisplayValue(dateTime, locale);
    } catch {
        return getDisplayValue(dateTime, undefined);
    }
};

export default getLocalizedDateTime;
