import { HttpErrorResponse } from '@angular/common/http';
import { Component, NgZone, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { BaseComponent } from '@common/base/base.component';
import { LoggingService } from '@app/core/services/logging/logging-service';
import { SamlLoginService } from '@app/core/services/saml-login.service';
import { TranslateService } from '@ngx-translate/core';
import { takeUntil } from 'rxjs/operators';
import { AuthService } from '@app/core/services/auth/auth.service';
import { AuthProvider } from '@app/core/common/enum/auth-provider';
import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service';

@Component({
	template: ''
})
export class SamlResponseLoginComponent extends BaseComponent implements OnInit {

	constructor(
		private route: ActivatedRoute,
		private samlLoginService: SamlLoginService,
		private router: Router,
		private uiNotificationService: UiNotificationService,
		private loggingService: LoggingService,
		private zone: NgZone,
		private language: TranslateService,
		private authService: AuthService,
	) { super(); }

	ngOnInit() {
		this.route.queryParams
			.pipe(takeUntil(this._destroyed))
			.subscribe(routeParams => {
				let samlResponse = null;
				if (routeParams.SAMLart) {
					samlResponse = routeParams.SAMLart;
				} else if (routeParams.SAMLResponse) {
					samlResponse = routeParams.SAMLResponse;
				}
				else if(routeParams.token){
					this.authService.getUserFromToken(routeParams.token).pipe(takeUntil(this._destroyed))
					.subscribe((result) => this.onAuthenticateSuccess(), (error) => this.onAuthenticateError(error));
					return;
				}

				if (samlResponse == null) this.router.navigate(['/login']);

				const spId = this.samlLoginService.resolveSpId(routeParams.RelayState);
				const configurableLoginId = this.samlLoginService.resolveConfigurableLoginId(routeParams.RelayState);

				this.authService.login({ ticket: samlResponse, provider: AuthProvider.Configurable, data: { configurableLoginId: configurableLoginId } })
				.pipe(takeUntil(this._destroyed))
				.subscribe((result) => this.onAuthenticateSuccess(), (error) => this.onAuthenticateError(error));
					
			});
	}

	onAuthenticateSuccess(): void {
		this.loggingService.info('Successful Login');
		this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-LOGIN'), SnackBarNotificationLevel.Success);
		this.zone.run(() => this.router.navigate(['/']));
	}

	onAuthenticateError(errorResponse: HttpErrorResponse) {
		this.uiNotificationService.snackBarNotification(errorResponse.error.message, SnackBarNotificationLevel.Warning);
		this.zone.run(() => this.router.navigate(['/']));
	}

}