import { 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 { BaseHttpService } from '@app/core/services/http/base-http.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 { FormControl } from '@angular/forms';
import { stringify } from 'querystring';

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

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

	constructor(
		private route: ActivatedRoute,
		private authService: AuthService,
		private httpClient: BaseHttpService,
		private loginService: LoginService,
		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['oauth_token'] && !params['oauth_verifier']) { this.twitterAuthorize(); } else { this.twitterLogin(params['oauth_token'], params['oauth_verifier']); }
				this.router.navigate(['/oauth2'], {queryParams: params});
			});
	}

	public twitterAuthorize() {
		let headers = new HttpHeaders();
		headers = headers.set('Content-Type', 'application/json');
		headers = headers.set('Accept', 'application/json');
		this.httpClient.get(this.configurationService.server + 'auth/twitterRequestToken', { headers: headers })
			.pipe(takeUntil(this._destroyed))
			.subscribe((data: any) => {
				window.location.href = this.configurationService.loginProviders.twitterConfiguration.oauthUrl + '?oauth_token=' + data.payload.value;
			});
	}

	public twitterLogin(token: string, verifier: string) {
		const data = {
			email: this.emailFormControl.value, verifier: verifier
		};
		this.authService.login({ ticket: token, provider: AuthProvider.Twitter, data: data })
			.pipe(takeUntil(this._destroyed))
			.subscribe(
				res => this.loginService.onLogInSuccess(res, this.returnUrl),
				error => this.loginService.onLogInError(error)
			);
	}
}
