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 { AuthService } from '@app/core/services/auth/auth.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';

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

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

	ngOnInit(): void {
		this.route.queryParams
			.pipe(takeUntil(this._destroyed))
			.subscribe((params: Params) => {
				// const returnUrlFromParams = params['returnUrl'];
				// if (returnUrlFromParams) { this.returnUrl = returnUrlFromParams; }
				// if (!params['code']) { this.openaireAuthorize(); } else { this.openaireLoginUser(params['code'], params['state']) }
				this.router.navigate(['/oauth2'], {queryParams: params});
			})
	}

	public openaireAuthorize() {
		window.location.href = this.configurationService.loginProviders.openAireConfiguration.oauthUrl
			+ '?response_type=code&client_id=' + this.configurationService.loginProviders.openAireConfiguration.clientId
			+ '&redirect_uri=' + this.configurationService.loginProviders.openAireConfiguration.redirectUri
			+ '&state=' + this.configurationService.loginProviders.openAireConfiguration.state
			+ '&scope=openid profile email';
	}

	public openaireLoginUser(code: string, state: string) {
		if (state !== this.configurationService.loginProviders.openAireConfiguration.state) {
			this.router.navigate(['/login'])
		}
		this.httpClient.post(this.configurationService.server + 'auth/openAireRequestToken', { code: code, provider: AuthProvider.OpenAire })
			.pipe(takeUntil(this._destroyed))
			.subscribe((data: any) => {
				this.authService.login({ ticket: data.payload.accessToken, provider: AuthProvider.OpenAire, data: null })
					.pipe(takeUntil(this._destroyed))
					.subscribe(
						res => this.loginService.onLogInSuccess(res, this.returnUrl),
						error => this.loginService.onLogInError(error)
					);
			});
	}
}
