import { DatePipe, registerLocaleData } from '@angular/common';
import localeEl from '@angular/common/locales/el';
import localeDe from '@angular/common/locales/de';
import localeEs from '@angular/common/locales/es';
import localeSk from '@angular/common/locales/sk';
import localeTr from '@angular/common/locales/tr';
import localeSr from '@angular/common/locales/sr';
import localePt from '@angular/common/locales/pt';
import { Pipe, PipeTransform } from '@angular/core';
import { LangChangeEvent, TranslateService } from '@ngx-translate/core';
import 'moment-timezone';
import { CultureInfo } from '../model/culture-info';
import { LanguageService } from '../services/language/language.service';

const availableCultures: CultureInfo[] = require('../../../assets/localization/available-cultures.json');

@Pipe({
	name: 'dateTimeCultureFormatter',
	pure: false
})
export class DateTimeCultureFormatPipe implements PipeTransform {
	private cultureValues = new Map<string, CultureInfo>(); // cultures by name
	private cache;

	constructor(private datePipe: DatePipe,
		private translate: TranslateService,
		private languageService: LanguageService) {

		if (availableCultures) {
			this.cultureValues = new Map<string, CultureInfo>();
			availableCultures.forEach(culture => {
				this.cultureValues.set(culture.name, culture);
			});
		}

		this.translate.onLangChange.subscribe(($event: LangChangeEvent) => {
			(<any>this).locale = $event.lang;
			this.cache = null;
		});
	}

	transform(value: any, format?: string, timezone?: string): string | null {
		if (!this.cache) {
			const cultureName = this.languageService.getCurrentLanguage();
			let locale: string;
			switch (cultureName) {
				case 'en': {
					locale = this.cultureValues.get('en-US').name;
					break;
				}
				case 'gr': {
					locale = this.cultureValues.get('el-GR').name;
					registerLocaleData(localeEl);
					break;
				}
				case 'es': {
					locale = this.cultureValues.get('es-ES').name;
					registerLocaleData(localeEs);
					break;
				}
				case 'de': {
					locale = this.cultureValues.get('de-DE').name;
					registerLocaleData(localeDe);
					break;
				}
				case 'tr': {
					locale = this.cultureValues.get('tr-TR').name;
					registerLocaleData(localeTr);
					break;
				}
				case 'sk': {
					locale = this.cultureValues.get('sk-SK').name;
					registerLocaleData(localeSk);
					break;
				}
				case 'sr': {
					locale = this.cultureValues.get('sr-Latn-RS').name;
					registerLocaleData(localeSr);
					break;
				}
				case 'pt': {
					locale = this.cultureValues.get('pt-PT').name;
					registerLocaleData(localePt);
					break;
				}
				default: {
					locale = this.cultureValues.get('en-US').name;
					break;
				}
			}
			this.cache = this.datePipe.transform(value, format, timezone, locale);
		}
		return this.cache;
	}
}
