import { UserInfo } from 'app/models/userInfo.model';
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { LocalStorageService } from 'angular-2-local-storage';
import {Router} from '@angular/router';
import { environment } from '../../environments/environment.dev';

@Component({
  selector: 'fbRedirectComponent',
  templateUrl: './fb.redirectUrl.html',
  styleUrls: ['./social.redirectUrl.css']
})
export class fbRedirectComponent {

  error: any;
  isEmailError = false;
  isPwdError = false;
  isError = false;
  isLoading =false;
  errorMessage = '';
  loginemailErrMsg ='';
  output: any;

  userData :{}

  imageUrl: string = environment.imageUrl;

  constructor(protected localStorageService: LocalStorageService,private AuthService:AuthService, private router:Router) {


    console.log(window.location.origin, 'Host')
    //var index = window.location.search;
    console.log(window.location.href, 'Full Url')
    // var code=window.location.hash.substring(index+1);


    var str = window.location.href

    let idpType
    let authCode

    var pattfb = new RegExp("facebookIdentity");
    var resfb = pattfb.test(str);

    var pattl = new RegExp("linkedInIdentity");
    var resl = pattl.test(str);


    var pattg = new RegExp("googleIdentity");
    var resg = pattg.test(str);

    var patto = new RegExp("o365Identity");
    var reso = patto.test(str);

    var pattda = new RegExp("o365DavintaIdentity");
    var resda = pattda.test(str);

    if(resfb){
      idpType = "facebookIdentity"
    }
    else if(resl){
      idpType = "linkedInIdentity"

    }
    else if(resg){
      idpType = "googleIdentity"
    }
    else if(reso){
      idpType = "o365Identity"
    }
    else if(resda){
      idpType = "o365DavintaIdentity"
    }
    else {

    }

    var searchParams = new URLSearchParams(window.location.search); //?anything=123
    authCode =searchParams.get("code")

    console.log(authCode,idpType)



    let toArray = window.location.search.split("code=");
    console.log(toArray);

    if(!authCode){

    }
    else{

      this.isLoading = true;
      this.AuthService.socialLoginNew({redirect_uri : window.location.origin+"/"+idpType,"byAuthCode" : true,authCode:authCode,idpType:idpType}).then(resp => {


        console.log(resp,"socialLoginNew")

        if(resp.status == 'success'){


          var userData = resp
          // this.localStorageService.set('authUserDetails',{name:'Sabash Lakshmanan',accessToken:resp});
         // localStorage.setItem('authToken',resp['accessToken']);
         // this.localStorageService.set('authToken',{accessToken:resp['accessToken'],loginType:'social'});


          this.AuthService.getUserDetails({accessToken:resp['accessToken'],idpType:idpType}).then(response => {



            if(response.status == 'success'){
              localStorage.setItem('authToken',resp['accessToken']);
             var  userDetails = JSON.parse(response['data'])
              console.log(userDetails,"getUserDetails")

              if (userDetails && userDetails.infoMstr && userDetails.infoMstr.pgRoleUser.length != 0) {

                console.log(userDetails.infoMstr.pgRoleUser[0].pgRolePrivilege.pgRoleMstr.roleName,'Role Detaiolssssssssssssssssssssssssssssssss')

                var role = userDetails.infoMstr.pgRoleUser[0].pgRolePrivilege.pgRoleMstr.roleName

                /*** O365 via login to check & redirect  ***/
                if (reso || resda) {

                  localStorage.setItem('EmpTtoken',resp['accessToken']);
                  // this.localStorageService.set('empInfo',{accessToken:resp['accessToken'],loginType:'social',fullName:userDetails.infoMstr.firstNm,userInfoMstrId:userDetails.infoMstr.userInfoMstrId,location:userDetails.infoMstr.location,skill:userDetails.infoMstr.pgSkillTrackDtls.skillTrackDtlsName});

                  console.log(userDetails,'User Detailsssssssssssss');
                  // Get user roles
                  const roles = [];
                  userDetails.infoMstr.pgRoleUser.forEach(usrRole => {
                    roles.push(usrRole.pgRolePrivilege.pgRoleMstr.roleName);
                  });

                  // to do null check for pgUserFileMapping
                  let profileImg
                  if(userDetails.infoMstr.pgUserFileMapping){
                    profileImg = userDetails.infoMstr.pgUserFileMapping.find(f => f.fileType === 'PROFILEIMAGE');
                  }

                  const json = {
                    accessToken: resp['accessToken'],
                    idpType: idpType,
                    adId: userDetails.infoDetails.adId,
                    fullName: userDetails.infoMstr.fullName,
                    firstName: userDetails.infoMstr.firstNm,
                    userInfoMstrId: userDetails.infoMstr.userInfoMstrId,
                    userInfoDtlsId: userDetails.infoDetails.userInfoDtlsId,
                    profileImgId: profileImg ? profileImg.fileId : null,
                    roleName: role,
                    roles: roles,
                    locationName: userDetails.infoMstr.pgLocation.city,
                    email: userDetails.infoMstr.emailId,
                    status: userDetails.infoMstr.status
                  };
                  console.log(json, 'userInfoDtlessss');
                  console.log(profileImg, 'profileImgValidation ');
                  this.localStorageService.set('userInfo', json);

                  if (role == 'TA' || role == 'COACH' || role == 'HEAD_COACH' || role == 'EMPLOYEE' || role == 'ADMIN' ){

                    this.router.navigate(['employee']);
                  }
                  else {
                    this.isError = true;
                    this.isLoading = false;
                    this.error = "Unauthorized Access Prohibited"
                  }


                }
                /*** Socail login to check & redirect  ***/
                else {
                  // this.localStorageService.set('authToken',{accessToken:resp['accessToken'],loginType:'social'});

                  localStorage.setItem('authToken',resp['accessToken']);
                  this.localStorageService.set('authToken',{accessToken:resp['accessToken'],idpType:idpType});

                  if(role == 'CANDIDATE'){
                    this.router.navigate(['introduction']);
                  }
                  else {
                    this.isError = true;
                    this.isLoading = false;
                    this.error = "Unauthorized Access Prohibited"
                  }

                }
              }
              else {
                this.isError = true;
                this.isLoading = false;
                this.error = "Please contact our Tanlent Acquisition team.."
              }




            }
            else {

              this.isError = true;
              this.isLoading = false;
              this.error = response['message']
            }


          }).catch(err=>{
            console.log(err)
            this.isError = true;
            this.isLoading = false;
            this.error = err['message']

          });


        }
        else{

          this.isError = true;
          this.isLoading = false;
          this.error = resp['message']

        }
      }).catch(err=>{
        console.log(err)
        this.isError = true;
        this.isLoading = false;
        this.error = err['message']

      });
    }


  }

}
