import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { AuthProvider } from '@app/core/common/enum/auth-provider';
import { OrcidUser } from '@app/core/model/orcid/orcidUser';
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-orcid-login',
	templateUrl: './orcid-login.component.html',
	styleUrls: ['./orcid-login.component.scss']
})
export class OrcidLoginComponent extends BaseComponent implements OnInit {

	private returnUrl: string;
	private orcidUser: OrcidUser
	private accessToken: string;
	private emailFormControl = new FormControl('');

	constructor(
		private route: ActivatedRoute,
		private authService: AuthService,
		private loginService: LoginService,
		private httpClient: HttpClient,
		private configurationService: ConfigurationService,
		private router: Router
	) {
		super();
		this.orcidUser = new OrcidUser;
	}

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

	public orcidAccessGetAuthCode() {
		window.location.href = this.configurationService.loginProviders.orcidConfiguration.oauthUrl
			+ '?client_id='
			+ this.configurationService.loginProviders.orcidConfiguration.clientId
			+ '&response_type=code&scope=/authenticate&redirect_uri='
			+ this.configurationService.loginProviders.orcidConfiguration.redirectUri;
	}

	public orcidLogin(code: string) {
		let headers = new HttpHeaders();
		headers = headers.set('Content-Type', 'application/json');
		headers = headers.set('Accept', 'application/json');
		this.httpClient.post(this.configurationService.server + 'auth/orcidRequestToken', { code: code }, { headers: headers })
			.pipe(takeUntil(this._destroyed))
			.subscribe((responseData: any) => {
				this.orcidUser.orcidId = responseData.payload.orcidId
				this.orcidUser.name = responseData.payload.name
				this.accessToken = responseData.payload.accessToken;
				this.authService.login({ ticket: this.accessToken, provider: AuthProvider.ORCID, data: this.orcidUser })
					.pipe(takeUntil(this._destroyed))
					.subscribe(
						res => this.loginService.onLogInSuccess(res, this.returnUrl),
						error => this.loginService.onLogInError(error)
					);
			});
	}

	public login() {
		this.orcidUser.email = this.emailFormControl.value;
		this.authService.login({ ticket: this.accessToken, provider: AuthProvider.ORCID, data: this.orcidUser })
			.pipe(takeUntil(this._destroyed))
			.subscribe(
				res => this.loginService.onLogInSuccess(res, this.returnUrl),
				error => this.loginService.onLogInError(error)
			);
	}
}
