import { Component, OnInit, OnDestroy, ViewChild, AfterViewInit, ChangeDetectorRef, AfterViewChecked, ElementRef, ViewChildren, QueryList } from '@angular/core';
import { LanguageService } from '@app/core/services/language/language.service';
import { BaseComponent } from '@common/base/base.component';
import { takeUntil } from 'rxjs/operators';
import { FormGroup, FormBuilder } from '@angular/forms';
import { TranslateService } from '@ngx-translate/core';
import { UiNotificationService, SnackBarNotificationLevel } from '@app/core/services/notification/ui-notification-service';
import { Router } from '@angular/router';
import { CdkTextareaAutosize } from '@angular/cdk/text-field';
import { MatomoService } from '@app/core/services/matomo/matomo-service';
import { HttpClient } from '@angular/common/http';

@Component({
	selector: 'app-language-editor',
	templateUrl: './language-editor.component.html',
	styleUrls: ['./language-editor.component.scss']
})
export class LanguageEditorComponent extends BaseComponent implements OnInit, AfterViewInit, OnDestroy {

	@ViewChildren('autosize', {read: CdkTextareaAutosize}) elements: QueryList<CdkTextareaAutosize>;

	readonly rowHeight = 100;
	readonly maxElements = 10;

	allkeys = [];
	keys = [];
	visibleKeys = [];
	startIndex = 0;
	endIndex: number;
	parseFinished = false;
	currentLang: string;
	formGroup: FormGroup;
	formBuilder: FormBuilder;

	constructor(
		private language: LanguageService,
		private uiNotificationService: UiNotificationService,
		private translate: TranslateService,
		private router: Router,
		private httpClient: HttpClient,
		private matomoService: MatomoService
	) { super(); }


	ngAfterViewInit(): void {
		this.elements.changes.pipe(takeUntil(this._destroyed)).subscribe(items => {
			if (this.elements.length > 0) {
				this.elements.toArray().forEach(autosize => {
					if (autosize instanceof CdkTextareaAutosize) {
						this.setupAutosize(autosize);
					} else {
						console.log(autosize);
					}
				})
			}
		});
	}

	ngOnInit() {
		this.matomoService.trackPageView('Admin: Language Editor');
		this.formBuilder = new FormBuilder();
		this.formGroup = this.formBuilder.group({});
		this.endIndex = this.maxElements;
		window.addEventListener('scroll', this.refreshFn, true);
		this.language.getCurrentLanguageJSON()
			.pipe(takeUntil(this._destroyed))
			.subscribe(response => {
				const blob = new Blob([response.body], { type: 'application/json' });
				this.convertBlobToJSON(blob);

			});
	}

	ngOnDestroy() {
		window.removeEventListener('scroll', this.refreshFn, true);
	}

	convertBlobToJSON(blob: Blob) {
		const fr = new FileReader();
		fr.onload = ev => {
			const langObj = JSON.parse(fr.result as string);
			this.convertObjectToForm(langObj, '', this.formGroup);
			this.currentLang = this.language.getCurrentLanguageName();
			this.keys.length = 0;
			for (const key of this.allkeys) {
				this.keys.push(key);
			}
			this.visibleKeys = this.keys.slice(this.startIndex, this.endIndex);
			this.parseFinished = true;

		};
		fr.readAsText(blob);
	}

	convertObjectToForm(obj: any, parentKey: string, form: FormGroup) {
		for (let prop in obj) {
			const key = parentKey !== '' ? `${parentKey}.${prop}` : prop;
			if (typeof obj[prop] === 'object') {
				form.addControl(prop, this.formBuilder.group({}));
				this.convertObjectToForm(obj[prop], key, form.get(prop) as FormGroup);
				continue;
			} else {
				form.addControl(prop, this.formBuilder.control(obj[prop]));
				this.allkeys.push(key);
			}
		}
		return;
	}

	updateLang() {
		const json = JSON.stringify(this.formGroup.value, null, "	");
		this.language.updateLanguage(json).pipe(takeUntil(this._destroyed))
			.subscribe(
				complete => {
					this.onCallbackSuccess(complete);
				},
				error => {
					this.onCallbackError(error);
				}
			);

	}

	onCallbackSuccess(id?: String): void {
		this.uiNotificationService.snackBarNotification(this.translate.instant('GENERAL.SNACK-BAR.SUCCESSFUL-UPDATE'), SnackBarNotificationLevel.Success);
		this.router.navigate(['/reload']).then(() => this.router.navigate(['/language-editor']));
	}

	onCallbackError(error: any) {
		this.uiNotificationService.snackBarNotification(error, SnackBarNotificationLevel.Error);
		//this.validateAllFormFields(this.formGroup);
	}

	refreshFn = (ev: Event) => {
		const evDoc = (<HTMLBaseElement>ev.target);
		let mainPage;
		evDoc.childNodes.forEach(child => {
			if ((<HTMLDivElement> child).id === 'main-page') {
				mainPage = child;
			}
		});
		if (document.scrollingElement !== undefined && mainPage !== undefined) {
			this.startIndex = Math.floor(evDoc.scrollTop / this.rowHeight);
			this.endIndex = this.startIndex + this.maxElements;
			const tempKeys = this.keys.slice(this.startIndex, this.endIndex);
			this.visibleKeys.length = 0;
			for (const key of tempKeys) {
				this.visibleKeys.push(key);
			}
		}
	}

	findKeys(ev: any) {
		let tempKeys = [];
		if (ev.value === "") {
			tempKeys = this.allkeys;
		} else {
			tempKeys = this.allkeys.filter((key) => (this.formGroup.get(key).value as string).toLowerCase().includes(ev.value.toLowerCase()));
			window.scrollTo({ top: 0 });
		}
		this.keys.length = 0;
		for (const key of tempKeys) {
			this.keys.push(key);
		}
		this.visibleKeys = this.keys.slice(this.startIndex, this.endIndex);
	}

	private setupAutosize(autosize: CdkTextareaAutosize) {
		if (autosize !== undefined && autosize !== null) {
			autosize.minRows = 1;
			autosize.maxRows = 5;
			autosize.enabled = true;
		}
	}

}
