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';

@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
	) {
		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() {
		let authUrl = this.provider.oauthUrl
			+ '?response_type=code&client_id=' + this.provider.clientId
			+ '&redirect_uri=' + this.provider.redirect_uri
			+ '&scope=' + this.provider.scope;
		if (this.provider.state.length > 0) authUrl = authUrl + '&state=' + this.provider.state
		window.location.href = authUrl;
	}

	public configurableLoginUser(code: string, state: string) {
		if (state !== this.provider.state) {
			this.router.navigate(['/login'])
		}
		this.httpClient.post(environment.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)
					)
			})
	}
}
