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';
import { ZenodoToken } from '@app/core/model/zenodo/zenodo-token.model';

@Component({
	selector: 'app-zenodo-login',
	templateUrl: './zenodo-login.component.html',
	styleUrls: ['./zenodo-login.component.scss']
})
export class ZenodoLoginComponent extends BaseComponent implements OnInit {

	private returnUrl: string;
	private zenodoToken: ZenodoToken
	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.zenodoToken = new ZenodoToken;
	}

	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.zenodoAccessGetAuthCode(); } else { this.zenodoLogin(params['code']); }
				this.router.navigate(['/oauth2'], {queryParams: params});
			});
	}

	public zenodoAccessGetAuthCode() {
		window.location.href = this.configurationService.loginProviders.zenodoConfiguration.oauthUrl
			+ '?client_id='
			+ this.configurationService.loginProviders.zenodoConfiguration.clientId
			+ '&response_type=code&scope=deposit:write+deposit:actions+user:email&state=astate&redirect_uri='
			+ this.configurationService.loginProviders.zenodoConfiguration.redirectUri;
	}

	public zenodoLogin(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/zenodoRequestToken', { code: code }, { headers: headers })
			.pipe(takeUntil(this._destroyed))
			.subscribe((responseData: any) => {
				this.zenodoToken.userId = responseData.payload.userId;
				this.zenodoToken.expiresIn = responseData.payload.expiresIn;
				this.accessToken = this.zenodoToken.accessToken = responseData.payload.accessToken;
				this.zenodoToken.email = responseData.payload.email;
				this.zenodoToken.refreshToken = responseData.payload.refreshToken;
				this.authService.login({ ticket: this.accessToken, provider: AuthProvider.Zenodo, data: this.zenodoToken })
					.pipe(takeUntil(this._destroyed))
					.subscribe(
						res => this.loginService.onLogInSuccess(res, this.returnUrl),
						error => this.loginService.onLogInError(error)
					);
			});
	}

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