import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';
import { environment } from '../../../environments/environment';
import { UserService } from '../../oneit/services/user.service';
import { AppService } from './../../app.service';
import { UtilsService } from './../../oneit/services/utils.service';


@Component({
    selector: 'app-login-options',
    templateUrl: './login-options.component.html'
})
export class LoginOptionsComponent implements OnInit, OnDestroy {

    subscriptions: Array<Subscription> = [];
    showLoader: boolean = false;
    showLogoutMessage: boolean = false;
    noLoginUser: boolean = false;

    constructor(private router: Router,
                private activatedRoute: ActivatedRoute,
                private appService: AppService,
                private utilsService: UtilsService,
                private userService: UserService) {
            }

    ngOnInit() {
        this.showLoader = true;

        this.subscriptions.push(this.userService.reloadUserDetails()
            .subscribe(
                data => {
                    this.showLoader = false;
                    const userID = this.userService.getUserid();

                    if (userID != null) {
                        this.noLoginUser = false;
                        this.router.navigate(['home']);
                        return;
                    }

                    this.noLoginUser = true;
                }
            )
        );

        this.activatedRoute.fragment.subscribe((fragment: string) => {
            if (fragment == 'logout') {
                this.showLogoutMessage = true;
            }
        });
    }

    socicalMediaLogin(type : string) {
        this.utilsService.clearErrorMessages();
        this.showLoader = true;
        const params = {
            environment: environment.envName,
            nextPage: window.location.href.split('/#/')[0] + '/#/registration/' + type
        };
        const svc = type === 'linkedIn' ? 'LoginWithLinkedIn' : 'LoginWithGoogle';

        this.subscriptions.push(this.appService.socicalMediaLogin(svc,params)
            .subscribe(
                data => {
                    if (data.destination) {
                        this.showLoader = false;
                        window.location.href = data.destination;
                        return;
                    }
                },
                error => {
                    this.showLoader = false;
                    this.utilsService.handleError(error);
                }
            )
        );
    }

    ngOnDestroy() {
        this.utilsService.unsubscribeSubscriptions(this.subscriptions);
    }
}
