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

@Component({
	selector: 'app-linkedin-login',
	templateUrl: './linkedin-login.component.html',
})
export class LinkedInLoginComponent extends BaseComponent implements OnInit {

	private returnUrl: string;

	constructor(
		private route: ActivatedRoute,
		private loginService: LoginService,
		private authService: AuthService,
		private router: Router,
		private httpClient: HttpClient
	) {
		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.linkedinAuthorize(); } else { this.linkedInLoginUser(params['code'], params['state']); }
			});
	}

	public linkedinAuthorize() {
		window.location.href = environment.loginProviders.linkedInConfiguration.oauthUrl
			+ '?response_type=code&client_id=' + environment.loginProviders.linkedInConfiguration.clientId
			+ '&redirect_uri=' + environment.loginProviders.linkedInConfiguration.redirectUri
			+ '&state=' + environment.loginProviders.linkedInConfiguration.state
			+ '&scope=r_emailaddress';
	}

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