import { Component, OnInit, HostListener } from '@angular/core';
import { Router } from '@angular/router';
import { Credential } from '@app/core/model/auth/credential';
import { AuthService } from '@app/core/services/auth/auth.service';
import { CultureService } from '@app/core/services/culture/culture-service';
import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service';
import { BaseComponent } from '@common/base/base.component';
import { TranslateService } from '@ngx-translate/core';
import { takeUntil } from 'rxjs/operators';
import { TranslateServerLoader } from '@app/core/services/language/server.loader';
import { LanguageService } from '@app/core/services/language/language.service';
@Component({
	selector: 'app-admin-login',
	templateUrl: './admin-login.component.html',
	styleUrls: ['./admin-login.component.scss']
})
export class AdminLoginComponent extends BaseComponent implements OnInit {

	public auth2: any;
	public credential: Credential;

	@HostListener('document:keydown.enter', ['$event']) onKeydownHandler() {
		this.nativeLogin();
	}

	constructor(
		private authService: AuthService,
		private uiNotificationService: UiNotificationService,
		private translate: TranslateService,
		private cultureService: CultureService,
		private router: Router,
		private language: LanguageService
	) { super(); }



	ngOnInit() {
		this.credential = {
			username: null,
			secret: null
		}
	}

	public nativeLogin() {
		this.authService.nativeLogin(this.credential)
			.pipe(takeUntil(this._destroyed))
			.subscribe(
				res => this.onLogInSuccess(res),
				error => this.onLogInError(error)
			);
	}

	public onLogInSuccess(loginResponse: any) {
		this.uiNotificationService.snackBarNotification(this.translate.instant('GENERAL.SNACK-BAR.SUCCESSFUL-LOGIN'), SnackBarNotificationLevel.Success);
		if (this.authService.current().culture) { this.cultureService.cultureSelected(this.authService.current().culture); }
		if (this.authService.current().language) { this.language.changeLanguage(this.authService.current().language); }
		this.router.navigate(['/']);
	}

	public onLogInError(errorMessage: string) {
		this.uiNotificationService.snackBarNotification(this.translate.instant('GENERAL.SNACK-BAR.UNSUCCESSFUL-LOGIN'), SnackBarNotificationLevel.Error);
	}
}
