import { HttpClient, HttpHeaders } 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-b2access-login',
	templateUrl: './b2access-login.component.html',
})
export class B2AccessLoginComponent extends BaseComponent implements OnInit {

	private returnUrl: string;

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

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

	public b2AccessGetAuthCode() {
		window.location.href = this.configurationService.loginProviders.b2accessConfiguration.oauthUrl
			+ '?response_type=code&client_id=' + this.configurationService.loginProviders.b2accessConfiguration.clientId
			+ '&redirect_uri=' + this.configurationService.loginProviders.b2accessConfiguration.redirectUri
			+ '&state=' + this.configurationService.loginProviders.b2accessConfiguration.state
			+ '&scope=USER_PROFILE';
	}

	public b2AccessLogin(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/b2AccessRequestToken', { code: code }, { headers: headers })
			.pipe(takeUntil(this._destroyed))
			.subscribe((data: any) => {
				this.authService.login({ ticket: data.payload.accessToken, provider: AuthProvider.B2Access, data: null })
					.pipe(takeUntil(this._destroyed))
					.subscribe(
						res => this.loginService.onLogInSuccess(res, this.returnUrl),
						error => this.loginService.onLogInError(error)
					);
			});
	}
}
