import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Params, Router } from '@angular/router';
import { AuthProvider } from '@app/core/common/enum/auth-provider';
import { ConfigurableProvider } from '@app/core/model/configurable-provider/configurableProvider';
import { AuthService } from '@app/core/services/auth/auth.service';
import { ConfigurableProvidersService } from '@app/ui/auth/login/utilities/configurableProviders.service';
import { LoginService } from '@app/ui/auth/login/utilities/login.service';
import { BaseComponent } from '@common/base/base.component';
import { environment } from 'environments/environment';
import { takeUntil } from 'rxjs/operators';
import { ConfigurationService } from '@app/core/services/configuration/configuration.service';
import { SamlLoginService } from '@app/core/services/saml-login.service';
import { Oauth2ConfigurableProvider } from '@app/core/model/configurable-provider/oauth2ConfigurableProvider';
import { Saml2ConfigurableProvider } from '@app/core/model/configurable-provider/saml2ConfigurableProvider';
import { ConfigurableProviderType } from '@app/core/common/enum/configurable-provider-type';

@Component({
	selector: 'app-configurable-login',
	templateUrl: './configurable-login.component.html',
})
export class ConfigurableLoginComponent extends BaseComponent implements OnInit {
	private returnUrl: string;

	// private configurableLoginId: string;
	// private clientId: string;
	// private oauthUrl: string;
	// private redirectUri: string;
	// private state: string;
	// @Input() scope: string;

	private provider: ConfigurableProvider;
	private providerId: string;

	constructor(
		private route: ActivatedRoute,
		private loginService: LoginService,
		private authService: AuthService,
		private router: Router,
		private httpClient: HttpClient,
		private providers: ConfigurableProvidersService,
		private configurationService: ConfigurationService,
		private samlLoginService: SamlLoginService
	) {
		super();
	}

	ngOnInit(): void {
		const params = this.route.snapshot.params;
		this.providerId = params['id'];
		if (this.providers.providers === undefined) {
			this.authService.getConfigurableProviders()
				.pipe(takeUntil(this._destroyed))
				.subscribe((data) => {
					this.providers.providers = data;
					this.provider = this.providers.providers.find(item => item.configurableLoginId == this.providerId)
					this.route.queryParams
						.pipe(takeUntil(this._destroyed))
						.subscribe((params: Params) => {
							const returnUrlFromParams = params['returnUrl'];
							if (returnUrlFromParams) { this.returnUrl = returnUrlFromParams; }
							if (!params['code']) { this.configurableAuthorize(); } else { this.configurableLoginUser(params['code'], params['state']) }
						})
				});
		} else {
			this.provider = this.providers.providers.find(item => item.configurableLoginId == this.providerId)
			this.route.queryParams
				.pipe(takeUntil(this._destroyed))
				.subscribe((params: Params) => {
					const returnUrlFromParams = params['returnUrl'];
					if (returnUrlFromParams) { this.returnUrl = returnUrlFromParams; }
					if (!params['code']) { this.configurableAuthorize(); } else { this.configurableLoginUser(params['code'], params['state']) }
				})
		}
	}

	public configurableAuthorize() {
		if(this.provider.type === ConfigurableProviderType.Oauth2){
			let provider = this.provider as Oauth2ConfigurableProvider;
			let authUrl = provider.oauthUrl
				+ '?response_type=code&client_id=' + provider.clientId
				+ '&redirect_uri=' + provider.redirect_uri
				+ '&scope=' + provider.scope;
				if (provider.state.length > 0) authUrl = authUrl + '&state=' + provider.state
				window.location.href = authUrl;
		}
		else if(this.provider.type === ConfigurableProviderType.Saml2){
			let provider = this.provider as Saml2ConfigurableProvider;
			window.location.href = this.samlLoginService.getSamlLoginUrl(provider.spEntityId, provider.idpUrl, provider.binding, provider.assertionConsumerServiceUrl, provider.configurableLoginId);
		}
	}

	public configurableLoginUser(code: string, state: string) {
		if (state !== (<Oauth2ConfigurableProvider>this.provider).state) {
			this.router.navigate(['/login'])
		}
		this.httpClient.post(this.configurationService.server + 'auth/configurableProviderRequestToken', { code: code, provider: AuthProvider.Configurable, configurableLoginId: this.providerId })
			.pipe(takeUntil(this._destroyed))
			.subscribe((data: any) => {
				this.authService.login({ ticket: data.payload.accessToken, provider: AuthProvider.Configurable, data: { configurableLoginId: this.provider.configurableLoginId } })
					.pipe(takeUntil(this._destroyed))
					.subscribe(
						res => this.loginService.onLogInSuccess(res, this.returnUrl),
						error => this.loginService.onLogInError(error)
					)
			})
	}
}
