import { Component, Input } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { LocalStorageService } from 'angular-2-local-storage';
import { Router } from '@angular/router';
import { log } from "util";
// import { FormControl, Validators } from '@angular/forms';
import { FormGroup, FormBuilder, FormsModule, FormControl, Validators, FormArray } from '@angular/forms';
import {IMyDrpOptions} from "mydaterangepicker";
import { environment } from '../../environments/environment.dev';
//Compounent decleration part  here
@Component({
  selector: 'login-com',
  templateUrl: './log.component.html',
  styleUrls: ['./log.component.css'],
})

// exports the class here..!
export class LoginComponent {


  public selectedTab = 0;
  @Input() email: string = '';
  @Input() password: string = '';
  @Input() confirm_password: string = '';
  // @Input() verificationCode:string = '';
  @Input() uidai:string = '';
  error: any;
  isEmailError = false;
  isPwdError = false;
  isError = false;
  isPhonerror: boolean = false;
  isSuccess = false;
  isLoading = false;
  firstNameError = false;
  lastNameError = false;
  institutionError = false;
  aadhaarError = false;
  verfCodeError = false;
  aadhaarErrMsg = '';
  errorMessage = '';
  successMessage = '';
  loginemailErrMsg = 'Please provide a valid email';
  phoneErrMsg = '';
  firstNameErrMsg = '';
  lastNameErrMsg = '';
  institutionErrMsg = '';
  verfCodeErrMsg = '';
  vcodeErrMsg ='';
  output: any;
  isConfirmPwdError = false;
  PwdErrMsg = '';
  comPwdErrMsg = '';
  signemailErrMsg = '';
  showsignup = false;
  showcard = 'login';
  respData: any;
  signupFirstStep: boolean = true;
  bnyregreq: boolean = false;
  phoneregex:RegExp = /^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[0123456789]\d{9}$/;
  preferredCountries = ['us', 'au', 'ru', 'gb', 'in'];
  userPresenceStatus: boolean;
  erroDiv: boolean = false;
  userData: {

    infoDetails: {},
    infoMstr: {},
    error: boolean
  }
  emailFormControl = new FormControl('', [
    Validators.required,
    Validators.email,
  ]);
  phoneFormControl = new FormControl('', [
    Validators.required,
     Validators.pattern(this.phoneregex),
  ]);
  hide = true;
  user: any = {}
  showForgotPassword: boolean = false;
  verfCodeSent: boolean = false;
  institutes: any;
  instEntered: string;
  instSelected: string;
  OverallError: boolean = false;
  tenthError: boolean = false;
  twelError: boolean = false;
  priSkillError: boolean = false;
  secSkillError: boolean = false;
  birthdayErr: boolean = false;
  birthdayErMsg = ''
  OverallErrMsg = '';
  tenthErrMsg = '';
  twelErrMsg = '';
  secSkillErrMsg = '';
  priSkillErrMsg = '';
  otherCollegeIp:boolean = false;
  isLinear = false;
  firstFormGroup: FormGroup;
  secondFormGroup: FormGroup;
  thirdFormGroup: FormGroup;
  genders: string[]  = ["Male","Female", "Other"];
  sems: string[]  = ["1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th"];
  idtypes: string[]  = ["Aadhaar", "College ID"];
  idDefault: string = "Aadhaar";

  myDateRangePickerOptions: IMyDrpOptions = {
    // other options...
    dateFormat: 'dd.mm.yyyy',
    disableSince:  {year: 2005, month: 9, day: 22},
    alignSelectorRight: true,
    openSelectorOnInputClick: true
  };

  // pwdPattern = "^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).{6,12}$";
  mobnumPattern = /^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[0123456789]\d{9}$/; 
  emailPattern = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  percentagePattern = /^\d+(\.\d{1,2})?$/;
  signUpSuccess = '';
  onlyText = /^[a-zA-Z ]*$/;
  public instCtrl: FormControl = new FormControl();
  imgUrl = environment.imageUrl;
  showPasswordField: boolean = false;
  showUserRegistration: boolean = false;
  pwdLengthErrorMsg = 'Password is minimum 6 characters';
  constructor(protected localStorageService: LocalStorageService, private AuthService: AuthService, private router: Router, private _formBuilder: FormBuilder) {

    // console.log("page Inittttttttttttttttttttt");
    // console.log(window.location.origin, 'Host');
    var index = window.location.hash;
    // var code=window.location.hash.substring(index+1);

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

    if (toArray.length <= 1) {

    }
    else {
      this.isLoading = true;
      this.AuthService.socialLogin({ code: toArray[1], redirectUrl: window.location.origin }).then(resp => {
        //this.output = res;

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

          this.AuthService.userDetails({ accessToken: resp['accessToken'], loginType: 'social' }).then(resp => {

            this.userData = resp;
            this.output = resp;
            console.log(this.userData);
            console.log(this.output);

            console.log(this.userData.infoDetails);
            console.log(this.userData['infoDetails']);
            console.log(this.userData['error']);

            if (this.output.status == 'error') {
              this.isError = true;
              this.isLoading = false;
              this.error = this.output.message;
              setTimeout(() => {
                this.isError = false;
                this.router.navigate(['']);
              }, 10000);
            }
            else if (this.userData) {
              this.router.navigate(['introduction']);
            }
            else {
              this.isError = true;
              this.isLoading = false;
              this.error = this.output.message;
              setTimeout(() => {
                this.isError = false;
                this.router.navigate(['']);
              }, 10000);
            }

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

          //this.router.navigate(['introduction']);
        }
        else {
          this.isError = true;
          this.isLoading = false;
          this.error = resp['message'];
          setTimeout(() => {
            this.isError = false;
            this.router.navigate(['']);
          }, 6000);
        }
      }).catch(err => {
        console.log(err);
        this.isError = true;
        this.isLoading = false;
        this.error = err['message'];
        setTimeout(() => {
          this.isError = false;
          this.router.navigate(['']);
        }, 6000);
      });
    }
    this.localStorageService.clearAll();
    localStorage.clear();
    // console.log('phone number is ',this.phonenumber)
    // if(this.thirdFormGroup.value.college = "Other"){
    //   this.otherCollegeIp = true;
    // }
    // this.secondFormGroup.controls['govType'].setValue(this.idDefault, {onlySelf: true})
  }

  //social Login click function

  ngOnInit() {

    console.log("page On inti only");
    this.institutes = [{name:'CIT Coimbatore Institute of Technology', id:'CIT'}, {name:'GCT Government College Of Technology', id:'GCT'}, {name:'MS College of Engineering, Bangalore', id:'MS'}, {name:'Vellore Institute of Engineering, Vellore', id:'VIE'}, {name:'College of Engineering- Guindy', id:'CIG'}, {name:'Madras Institute of Technology, Chennai', id:'MITC'}, {name:'RV College of Engineering, Bangalore', id:'RVCE'}, {name:'Other', id:'oth'}];
    this.genders = ["Male","Female", "Other"];
    this.sems = ["1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th"];
    this.idtypes = ["Aadhaar", "College ID"];
    //console.log(this.signUpSuccess);
    // this.firstFormGroup = this._formBuilder.group({
    //   firstCtrl: ['', Validators.required]
    // });
    // this.secondFormGroup = this._formBuilder.group({
    //   secondCtrl: ['', Validators.required]
    // });
  }
 

  socialBtn(idpType) {
    console.log(idpType);
    this.AuthService.getSocialLogins({ idpType: idpType, redirect_uri: window.location.origin + '/' + idpType }).then(resp => {
      console.log(resp);
      console.log(resp['loginUrl']);

      if (resp['loginUrl'] === undefined || resp['loginUrl'] === null) {
        alert('getSocialLogins API login failed' + JSON.stringify(resp));
        this.router.navigate(['']);
      }else {
        window.location.href = resp['loginUrl'];
      }
    }).catch(err => {
      console.log(err)
      this.isError = true;
      this.isLoading = false;
      this.error = err['message']
      setTimeout(() => {
        this.isError = false;
        this.router.navigate(['']);
      }, 6000);
    });

    //  var link = "https://www.facebook.com/v2.10/dialog/oauth?client_id=1408673912550613&redirect_uri=http://localhost:8080&scope=email"
    //window.location.href = 'https://www.facebook.com/v2.10/dialog/oauth?client_id=1408673912550613&redirect_uri='+window.location.origin+'&&scope=email';
  }


  //social Login once entered the EmailId and focusout from Email box
  OnFocusOutLogin() {
   // this.email = this.myForm.value.email;
  if(this.emailFormControl.valid) {
    let domainName = this.email.substring(this.email.lastIndexOf("@") + 1).toLowerCase();
    console.log(domainName);
    let IdpName: string;
    if (domainName === 'altimetrik.com') {
      this.isLoading = true;
      IdpName = 'o365Identity';
       this.socialBtn(IdpName)
    } else if (domainName === 'davinta.com') {
      this.isLoading = true;
      IdpName = 'o365DavintaIdentity';
       this.socialBtn(IdpName)
    }else {
      console.log('id is not alti not davinta')
      this.AuthService.getStatusVerifyEmailId(this.email).then((res) => {
        console.log('service success');
        console.log(res)
        if (res.nextAction === 'Register') {
          // this takes to the candidate registration flow.
          this.localStorageService.set('emailForSignUp', this.email);
          this.router.navigate(['signup']);
        } else if (res.nextAction === 'Login') {
          this.showPasswordField = true;
        } else if (res.nextAction === 'Signup') {
          this.showUserRegistration = true;
        }
      })
    }
  } 
  }


  //Login Button click function here..
  login() {

    // call AuthService Login function here...!
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

    this.isPwdError = false;
    this.isEmailError = false;
    this.isError = false;
    this.isLoading = false;
    if (this.password.length <= 5) {
      this.isPwdError = true;
      this.errorMessage = "Password is minimum 6 characters.";
    }
    if (this.password == null || this.password == '' || this.password == undefined) {
      this.isPwdError = true;
      this.errorMessage = "Please provide a valid password.";
    }
    if (this.email == null || this.email == "" || this.email == undefined || !re.test(this.email)) {
      //alert(this.email)
      this.isEmailError = true;
      this.loginemailErrMsg = "Please provide a valid email.";
    }
    if (!this.isPwdError && !this.isEmailError) {
      this.isLoading = true;
      let domainName = this.email.substring(this.email.lastIndexOf("@") + 1).toLowerCase();
      console.log(domainName);
      let IdpName: string;
      if (domainName === 'altimetrik.com') {
        IdpName = 'o365Identity';
      } else if (domainName === 'davinta.com') {
        IdpName = 'o365DavintaIdentity';
      } else {
        IdpName = 'databaseIdentity';
      }
      console.log(' *************  get IdpName ' + IdpName);
      if (IdpName === 'o365Identity' || IdpName === 'o365DavintaIdentity') {
        this.socialBtn(IdpName);
      } else {
        this.AuthService.login({ username: this.email, password: this.password, idpType: 'databaseIdentity', redirect_uri: window.location.origin + '/databaseIdentity' }).then(res => {
          this.output = res;
          console.log(this.output);
          console.log(this.output.status);
          if (this.output.status == 'success') {
            // alert(this.output.status)
            //this.output = JSON.parse(res)
            console.log(this.output.data, 'logon Db response');
            this.isLoading = false;
            console.log(this.output.data['tokenVO']);
            console.log(this.output.data.tokenVO['access_token']);
            // this.localStorageService.set('authUserDetails',{name:'Sabash Lakshmanan',accessToken:this.output.userDetailsBean.access_token});
            localStorage.setItem('token', this.output.data.tokenVO['access_token']);
            this.localStorageService.set('authToken', { accessToken: this.output.data.tokenVO['access_token'], idpType: 'databaseIdentity' });
           // this.router.navigate(['introduction']);
            this.AuthService.getUserDetails({accessToken:this.output.data.tokenVO['access_token'],idpType:'databaseIdentity'}).then(response => {
              if(response.status == 'success'){
                localStorage.setItem('authToken',this.output.data.tokenVO['access_token']);
                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  ***/
                  localStorage.setItem('EmpTtoken',this.output.data.tokenVO['access_token']);
                  // 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);
                  });
                  const profileImg = userDetails.infoMstr.pgUserFileMapping.find(f => f.fileType === 'PROFILEIMAGE');
                  const json = {
                    accessToken: this.output.data.tokenVO['access_token'],
                    idpType: 'databaseIdentity',
                    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,
                    email: userDetails.infoMstr.emailId,
                    status: userDetails.infoMstr.status
                  };
                  let loggedInDomainName = userDetails.infoDetails.pgUserInfoMstr.emailId.substring(userDetails.infoDetails.pgUserInfoMstr.emailId.lastIndexOf("@") + 1).toLowerCase();
                  console.log(json, 'userInfoDtlessss');
                  console.log(profileImg, 'profileImgValidation ');
                  this.localStorageService.set('userInfo', json);
                  if((loggedInDomainName == 'bnymellon.com') && (userDetails.infoDetails.firstTimeLogin == true)){
                    this.router.navigate(['employee/first-time']);
                  }
                  else if((loggedInDomainName == 'bnymellon.com') && (userDetails.infoDetails.firstTimeLogin == false)){
                    this.router.navigate(['employee/dashboard']);
                  }
                  else if(loggedInDomainName != 'bnymellon.com'){
                    if (role === 'CANDIDATE') {
                      this.router.navigate(['candidate/dashboard']);
                    }else {
                      this.router.navigate(['employee']);
                    }
                    // for otheremployees - O365 login
                  }
                  // this.router.navigate(['employee']);
                }
                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 if (this.output.status == 'error') {
            this.isError = true;
            this.isLoading = false;
            this.error = this.output.message;
            setTimeout(() => {
              this.isError = false;
            }, 6000);
          }
          else {
            this.isError = true;
            this.isLoading = false;
            this.error = this.output.message;
            setTimeout(() => {
              this.isError = false;
            }, 6000);
          }
        }).catch(err => {
          console.log(err);
          this.isError = true;
          this.isLoading = false;
          this.error = err['message'];
          setTimeout(() => {
            this.isError = false;
          }, 6000);
        });
      }
    }
  }
 
 
  editEmailEntered(){
    this.bnyregreq = false;
      this.signupFirstStep = true;
  }

  editStudentEmailEntered(){
    // this.studentFirstStep = true;
  }

  gotoFPpage(){
    console.log('coming here');
   // this.showForgotPassword = true;
    // this.verfCodeSent = true;
    this.router.navigate(['forgotpassword']);
  }
  
  onDateChanged(evnt){
    console.log(evnt)
  }

  registerCandidate() {
    console.log('registration is called');
    this.isConfirmPwdError = false;
    this.comPwdErrMsg = '';
    this.isError = false;
    if(this.password === this.confirm_password) {
      var regObj = {
        "email": this.email,
        "password": this.password,
        "firstName": "",
        "lastName": "",
        "fullName": ""
  
      }
      this.AuthService.registerCandidateWithOnlyPassword(regObj).then( (res: any)=>{
          // console.log(res);
          if(res.status === 'error') {
            this.isError = true;
            this.error = res.errorMessage;
          }else {
            console.log('registration success');
            this.isSuccess = true;
            this.successMessage = res.successMessage;
          }

          setTimeout(() => {
            this.showPasswordField = false;
            this.showUserRegistration = false;
            this.password = '';
            this.confirm_password = '';
            this.isError = false;
            this.isSuccess = false;
          }, 3000);
         
      }, error => {
        console.log(error);
      })
    }else {
      this.isConfirmPwdError = true;
      this.comPwdErrMsg = "Password mismatched.";
    }
   
    
  }

  goBackToLogin(){
    this.showForgotPassword = false;
  }
}

