import { environment } from './../../environments/environment';
import { Component, OnInit, ViewChild, EventEmitter,Output, OnDestroy, Inject } from '@angular/core';
import {FormGroup, FormControl, Validators} from '@angular/forms';
import {Contact} from '../contact';
import {ContactService} from '../contact.service';
import { Injectable } from '@angular/core';
import {Login} from '../login';
import {Otp} from '../otp';
import {CountDown} from "ng2-date-countdown";
import { Subscription } from 'rxjs/Rx';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import {MdDialog, MdSnackBar} from '@angular/material';
import { Title } from '@angular/platform-browser';

import { Http, Response } from '@angular/http';
import { NguiMessagePopupComponent, NguiPopupComponent} from '@ngui/popup';
import {DashComponent} from '../dash/dash.component';
// import {Md5} from 'ts-md5/dist/md5';
import { FlashMessagesService } from 'angular2-flash-messages';
import {Otp_log} from '../otp_log'
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import {Observable} from 'rxjs/Observable'; 
import { TranslateService } from 'ng2-translate';
import { DOCUMENT } from '@angular/common';
import { AnnouncementComponent } from '../const/announcement/announcement.component';
@Component({
  selector: 'app-services',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers: [ContactService],
  
})
@Injectable()
export class LoginComponent implements OnInit {
  initialLoginForm :boolean = true;
  resetPasswordTemplate:boolean = false;
  userNameCheck: Number;
    @ViewChild(NguiPopupComponent) popup: NguiPopupComponent;
    logins: Login[]=[];
    demoString = "Demo Request"; 
    login: Login;
    primaryContent:Boolean=true;
    contacts: Contact[]=[];
    contact: Contact;
    otp_logs: Otp_log[]=[];
    otp_log: Otp_log;
    first_name: string;
    tagline= 'Universal platform to track all kinds of GPS devices in just one click...#VehicleTracking#GPSPlatform';
    last_name: string;
    requestDemo : boolean = false; 
    username:any;
    organisationName : any ;
    emailf: boolean =true;
    otpf: boolean =false;
    otpg: boolean = false;
    email: string;
    buttonText = "Login";
    password: string;
    org_name: string;
   phone: string;
   message: string
  // login:any;
   login1:any;
   showLoader:boolean =false;
   showMenu = environment.showLandingpageMenu;
   loginList:any;
   conResponse:any;
   con:any;
   logmob:any;
   encryptedString:any
otp:any;
status:any;
executed:any;
j:any;
i=0;
mess:any

passwordIcon:any = "visibility_off";
  dealerid: any;
  android: any;
  iphone: any;
  hidePassword: boolean;
  showLink: boolean;
  backgroundImage: string;
  app_logo: string;
  logo_1: string ;
  cpn_showLink: boolean =false;
  mainSiteurl:any; 
  saanvi_showLink: boolean = false;
  urlIdentifier: string;
  supportContact: any;
  showNav: boolean;
  clientUrl: string;
  androidAppLink: any;
  iosAppLink: any;

  constructor(private titleServic: Title,public dialog: MdDialog,private dataService: ContactService,private _flashMessagesService: FlashMessagesService,private router: Router,public snackBar: MdSnackBar,public translate: TranslateService,@Inject(DOCUMENT) private _document: HTMLDocument) { 
    let split1 = document.URL.split('//')[1];
    console.log(split1,document); 
    let split2 = split1.split('/')[0]; 
    // let split3="gps.fleetpolice.com"
    // let split2= "login.cpntrack.com" ; 
  //  this.backgroundImage = '../../assets/image/login_bg.jpg';\

  this.clientUrl = split2 ; 
  
    console.log("this is split2 response",split2);
    if(split2 == "www.oneqlik.in"){ 
      this.showLink = true;
      this.mainSiteurl  = 'https://web.oneqlik.in/telematics/';
      this.backgroundImage = '../../assets/image/login_bg.jpg';
      this.logo_1  = '../../assets/image/f_logo.jpg' ; 
    }else{  
      console.log("Inside showlink false");
      this.showLink = false;
    }

    if(split2 == "login.cpntrack.com"){ 

      this.cpn_showLink = true;
      this.mainSiteurl  = 'http://www.cpntrack.com/';
    
    }

    if((split2 == "saanvisecurity.in")||(split2 == "www.saanvisecurity.in")){
      this.saanvi_showLink = true;
      this.mainSiteurl  = 'http://site.saanvisecurity.in';
    }

    if((split2 == "fastracxgps.in")||(split2 == "www.fastracxgps.in")||(split2 == "fastracxgps")){
      this.saanvi_showLink = true;
      this.mainSiteurl  = 'http://www.fastracxgps.com';
    }
   
    if((split2 == "e-fasttracksolutions")||(split2 == "tracknp.e-fasttracksolutions.com")){
      console.log('e-fasttracksol');
      // this.saanvi_showLink = true;
      this.primaryContent = false;
      this.mainSiteurl  = 'https://www.e-fasttracksolutions.com';
    }
    if(split2 == "fleetpolice.com" || split2 == "gps.fleetpolice.com"){
      this.mainSiteurl  = 'https://www.fleetpolice.com';
    }
   }
  adddev(){
    this.otpf = false ;
    this.emailf = true;
  }
  loginot(){
    // console.log("runnig OTP");
    this.emailf = false;
    // console.log("a");
    this.otpf = true ;
  }

  validatenum(num){

 var re1 = /^(\+91[\-\s]?)?[0]?(91)?[6789]\d{9}$/;
    return re1.test(num);
  }
  

  validateEmail(email) {
    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,}))$/;
    return re.test(email);
  }
  showError : boolean = false;

  setOrgInLocalStorage(data){
    // console.log("kdddddddddddddddddd",data,data.isSuperAdmin,data.isDealer);
    
    if(data.isSuperAdmin){
       console.log("kdddddddddddddddddd1111",data,data.isSuperAdmin,data.isDealer);
      this.dataService.getImagePath(data._id).subscribe(res=>{
         console.log("ssss","sas",res);
        if(res.organisation){
          localStorage.setItem('ORG',JSON.stringify(res.organisation))
        }else{
          localStorage.setItem('ORG',JSON.stringify(res))
        }
      })
    }else if(data.isDealer){
       console.log("kdddddddddddddddddd",data,data.isSuperAdmin,data.isDealer);
       this.dataService.getImagePath(data.supAdmin).subscribe(res=>{
         console.log("ssss","sas",res);
         
         if(res.organisation){
          localStorage.setItem('ORG',JSON.stringify(res.organisation))
        }else{
          localStorage.setItem('ORG',JSON.stringify(res))
        }
       
      })
    }
  }


  loginemail(){
    var that = this; 
    this.urlIdentifier = localStorage.getItem('referrer_token=');
    if(this.urlIdentifier != undefined){
    let loginInfo = JSON.parse(localStorage.getItem('referer_obj'));
    this.username = loginInfo.username; 
    this.password = loginInfo.pass; 
    }

   
  if((this.username==null) || (this.password == null))
  {
    var input = $('.validate-input .input100');

    $('.validate-form').on('submit',function(){
        var check = true;

        for(var i=0; i<input.length; i++) {
            if(that.uservalidate(input[i]) == false){
                that.showValidate(input[i]);
                check=false;
            }
        }

        return check;
    });


    $('.validate-form .input100').each(function(){
        $(this).focus(function(){
           that.hideValidate(this);
        });
    })
    
  } else{

    var  stringChk = this.username.trim();
    console.log(Number(this.username));
    if((stringChk.length == 10)&&(Number(this.username) > 0)){
      this.executed = true;
      const newlog ={
        ph_num: this.username.trim(),
        psd: this.password
    }
    this.showLoader = true;
    // debugger;
    this.dataService.log(newlog)
    .subscribe(login => {
      this.showLoader = false;
      this.logins.push(login);   
    //  console.log(JSON.parse("TOKEN",login.token));
      window.localStorage['token'] = login.token;
      this.setOrgInLocalStorage(JSON.parse(atob(login.token.split('.')[1])))
       window.localStorage['currentpwd'] = this.password;  
       localStorage.setItem('currentuser',JSON.parse(atob(login.token.split('.')[1]))._id);
      var isOperator  =  JSON.parse(atob(login.token.split('.')[1])).isOperator;
      var userId =  JSON.parse(atob(login.token.split('.')[1]))._id;

      this.getLanguage(userId,isOperator,JSON.parse(atob(login.token.split('.')[1])).customer_role);
   
    } , (err: any) => {
      //  console.log(err.status); 
      // console.log(err);
      this.showLoader = false;
    if(err.status !=   200)
    {
      this.showError = true; 
      this.mess = err._body.split("\"")[3];
      //console.log(this.mess);
    

      // this._flashMessagesService.show( this.mess, { cssClass: 'alert-danger', timeout: 1000 });
      
    }
    } );
    }
    else if(this.validateEmail(this.username)){
            // console.log("emailaddress");
            this.executed = true;
            const newlog ={
             emailid: this.username,
             psd: this.password
          }
          this.showLoader = true;
          this.dataService.log(newlog)
            .subscribe(login => {
              this.showLoader = false;
              this.logins.push(login);
              // console.log(JSON.parse("TOKEN",login.token));
              var isOperator  =  JSON.parse(atob(login.token.split('.')[1])).isOperator;
              console.log(isOperator);
              window.localStorage['token'] = login.token;
               this.setOrgInLocalStorage(JSON.parse(atob(login.token.split('.')[1])))
              window.localStorage['currentpwd'] = this.password
              localStorage.setItem('currentuser',JSON.parse(atob(login.token.split('.')[1]))._id);
              var userId =  JSON.parse(atob(login.token.split('.')[1]))._id;
              this.getLanguage(userId,isOperator,JSON.parse(atob(login.token.split('.')[1])).customer_role);
          
            }, (err: any) => {
              // console.log(err.status);
              // console.log(err);
              this.showLoader = false;
              if (err.status != 200) {
                this.showError = true; 
                this.mess = err._body.split("\"")[3];
                // console.log(this.mess);
                // this._flashMessagesService.show(this.mess, { cssClass: 'alert-danger', timeout: 1000 });

              }
            });
        
    }
    else{
     // console.log("hfdufgudsgfugdsufgukdsg")
    this.executed = true;
    const newlog ={
    user_id: this.username,
    psd: this.password
}
this.showLoader = true;
this.dataService.log(newlog)
.subscribe(login => {
  this.showLoader = false;
  this.logins.push(login);
  
  console.log(JSON.parse(atob(login.token.split('.')[1])));
  window.localStorage['token'] = login.token;
   this.setOrgInLocalStorage(JSON.parse(atob(login.token.split('.')[1])))
  window.localStorage['currentpwd'] = this.password
  localStorage.setItem('currentuser',JSON.parse(atob(login.token.split('.')[1]))._id);
  var isOperator  =  JSON.parse(atob(login.token.split('.')[1])).isOperator;
  console.log(isOperator);
  var userId =  JSON.parse(atob(login.token.split('.')[1]))._id;
  this.getLanguage(userId,isOperator,JSON.parse(atob(login.token.split('.')[1])).customer_role);

 

  //this.router.navigateByUrl("const?_i="+login.token);
} , (err: any) => {
  //  console.log(err.status); 
  
  this.showLoader = false;
if(err.status !=   200)
{
  this.mess = err._body.split("\"")[3];
 // console.log(this.mess);
 this.showError = true; 
  // this._flashMessagesService.show( this.mess, { cssClass: 'alert-danger', timeout: 1000 });
  
}
} );
    }
}}
mes:any;
view3:boolean = false;
loginn:boolean = true;
resetuname:any;

//Forgot Password
forgotPwd(){
  this.loginn = false;
  this.view3 = true;
}
forgotPwd2(){
  this.loginn = true;
  this.view3 = false;
}
rstemail:any;
rstcode:any;
rstbtn:any
rstbtn2:boolean=true;
password1:any;
psw:boolean=false;
password2:any;
rstemail2:any
otp3:any;
data_descip:any;

resetpassword(){
  if(this.password1 != this.password2){
    let message1="New Password and Reset Password do not match";
    let action:any;
    this.snackBar.open(message1, action, {
      duration: 5000,

      
    });  
    
    // this._flashMessagesService.show("New Password and Reset Password do not match", { cssClass: 'alert-danger', timeout: 1000 });
  }
  else{
    this.dataService.resetpwd(this.resetuname,this.otp3,this.password1).subscribe(
      
      (data) => {
        
        this.rstemail2 = data 
        // console.log(this.rstemail2)
        if(this.rstemail2.message == "Password Sucessfully Changes"){
          this.initialLoginForm = true;
          this.resetPasswordTemplate = false;
          this.tost1("PassSucc");
          let message1="Password changed successfully";
          let action:any;
          this.snackBar.open(message1, action, {
            duration: 5000,
            
          });  
         this.loginn = true;
         this.view3  = false;

          }
          else if(this.rstemail2.message == "Wrong OTP try again"){
            let message1="Wrong OTP try again";
            let action:any;
            this.snackBar.open(message1, action, {
              duration: 5000,
              
            });  
            // //console.log("C")
            // this._flashMessagesService.show("Wrong OTP", { cssClass: 'alert-danger', timeout: 1000 });
          }
    
      },
      (err: any) => {   
         if(err.status ==   500)
        {
          console.log(JSON.parse(err._body).message);
          var err_text_1 = JSON.parse(err._body).message;     
          let action:any;
          this.snackBar.open(err_text_1, action, {
            duration: 5000,
            
          });  
          // this.tost1("err")
        }
       }   
    )
  }
 
}
resetcode(){
  if(this.resetuname == null || this.resetuname == undefined || this.resetuname ==""){
    let message1="Please enter Email ID/Mobile Number";
    let action:any;
    this.snackBar.open(message1, action, {
      duration: 5000,
      
    });  
    // this._flashMessagesService.show("Please enter Email ID/Mobile Number", { cssClass: 'alert-danger', timeout: 1000 });
  }
 else{
  this.dataService.resetemail(this.resetuname).subscribe(
      
    (data) => {
      
      this.rstemail = data 
      if(this.rstemail.message == "OTP sent successfully"){
       this.resetPasswordTemplate = !this.resetPasswordTemplate;
       this.rstbtn2=false;
       this.rstcode=true
       this.rstbtn=true;
       this.psw=true;
       let message = "Reset Password OTP Sent to your mobile number";
       let action
       this.snackBar.open(message, action, {
         duration: 3000,
         
       });
      //  this._flashMessagesService.show("Reset Password OTP Sent to your mobile number", { cssClass: 'alert-success', timeout: 1000 });

        }
        else if(this.rstemail.message == "email sent"){
          this.resetPasswordTemplate = !this.resetPasswordTemplate;
          let message = "Reset Password Link Sent to your Email ID";
          let action
          this.snackBar.open(message, action, {
            duration: 3000,
            
          });
          // this._flashMessagesService.show("Reset Password Link Sent to your Email ID", { cssClass: 'alert-success', timeout: 1000 })
        }
     
  
    },
    (err)=>{
      
      if(err.status ==   500)
      {
        this.err_text = JSON.parse(err._body);
        this.tost1("err")
      }
    })
  }
} 

err_text:any;

loginotp(){
  if(this.username==null)
  {
    this._flashMessagesService.show('Enter Phone Number or password', { cssClass: 'alert-danger', timeout: 1000 });
    
  }
  else{
    this.executed = true;
  const newlog ={
   ph_num: this.username,
    otp: this.password
}

this.dataService.log(newlog)
.subscribe(login => {
  this.logins.push(login);
 console.log(JSON.parse("TOKEN",login.token));
 var tokenData=JSON.parse("TOKEN",login.token)
 window.localStorage['token'] = login.token
 window.localStorage['currentpwd'] = this.password
 localStorage.setItem('currentuser',JSON.parse(atob(login.token.split('.')[1]))._id);
//  if()
 this.router.navigateByUrl("const?_status="+"OK");
 // this.router.navigateByUrl("const?_i="+login.token);

} , (err: any) => { console.log(err.status); 
  // console.log(err);
if(err.status !=   200)
{
  this.mes = err._body.split("\"")[3];
  this._flashMessagesService.show(this.mes, { cssClass: 'alert-danger', timeout: 500 }); 
}
});
}}

cou :any;
 loginwithotp(){
    if(this.username==null)
    {
      this._flashMessagesService.show('Enter Mobile number', { cssClass: 'alert-danger', timeout: 1000 });
      
    }
    else{
    const newContact2 ={
      ph_num: this.username
  }
  this.dataService.addContact2(newContact2)
  .subscribe(contact => {
    this.contacts.push(contact);
  });
  this._flashMessagesService.show('OTP Sent Sucessfully', { cssClass: 'alert-success', timeout: 1000 });
  this.otpg=true;
  this.retry2=true;
  this.retry=false;
  this.countdown( "countdown", 9, 60 );
/*   this.countDown = Observable.timer(0,1000)
    .take(this.count)
    .map(()=> --this.count);
console.log(this.countDown)   */

  
 
  this.dataService.getContacts2()
  .subscribe(
    (data1 => this.login1 = data1)
  );
}}
 
 

/*     addContact2(value){
      if (!this.executed) {
        this.executed = true;
      const newContact2 ={
        phone: value
    }
    this.dataService.addContact2(newContact2)
    .subscribe(contact => {
      this.contacts.push(contact);
      
    });
    this._flashMessagesService.show('OTP Sent Sucessfully', { cssClass: 'alert-success', timeout: 3000 }); 
    
  }

    } */
  
    click1(event){
      if((event.keyCode >= 48 && event.keyCode <= 57) || event.keyCode == 9 || event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 37 || event.keyCode == 39){
      }
      /* if(event.keyCode===13){
      this.otp_window();
      } */
      
      else
      event.preventDefault();
      }
      
      countDown;
      count = 10;
      ticks = 0;


countdown( elementName, minutes, seconds )
{
    var element, endTime, hours, mins, msLeft, time;

    function twoDigits( n )
    {
        return (n <= 9 ? "0" + n : n);
    }

    function updateTimer()
    {
        msLeft = endTime - (+new Date);
        if ( msLeft < 1000 ) {
            element.innerHTML = "OTP Expired!!";
        } else {
            time = new Date( msLeft );
            hours = time.getUTCHours();
            mins = time.getUTCMinutes();
            element.innerHTML = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits( time.getUTCSeconds() );
            setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );
        }
    }

    element = 0;
    element = document.getElementById( elementName );
    endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
    updateTimer();
  }
  retry2 :boolean =false;
  retry:boolean =true;
  tost1(divid){
    if(divid == "dup_email"){
      this.data_descip = "Email ID Already Exists";
      launch_toast();
    }
    else if(divid == "Confirm_Email"){
      this.data_descip = "Confirmation Link Sent please check your Email ID"
      window.localStorage['Email'] = 'False'
      launch_toast();
    }
    else if(divid == "Confirm_Mobile"){
      this.data_descip = "Registered Successfully"
      window.localStorage['Mobile'] = 'False'
      launch_toast();
    }
    else if(divid == "EmM"){
      this.data_descip = "Mobile Verified Please Check Email"
      window.localStorage['EmailMobile'] = 'False'
      launch_toast();
    }
    else if(divid == "err"){
      this.data_descip = this.err_text.message
      launch_toast();
    }
      function launch_toast() {
       // console.log(divid);
        var x = document.getElementById("toast")
        //console.log(x);
        x.className = "show";
        setTimeout(function(){ x.className = x.className.replace("show", ""); }, 4500);
    }
     }
     url:any;
     userData:any;
     logo:any;
     titleService:any;
     text:any;
     dev_url=environment.hostUrl;
    
  ngOnInit() {
  
    this.dealerid =  window.localStorage['DealerID'];
    this.android =  window.localStorage['android'];
    // console.log(this.android)
    this.iphone =  window.localStorage['iphone'];

   

    if(window.localStorage.token){
      if( window.localStorage['Custumer'] == 'ON'){
        window.localStorage['token'] =  window.localStorage['Dealer_token'];
        window.localStorage['Custumer'] = 'OFF'
        this.router.navigateByUrl("const?_status="+"OK");
      }
      else{
        this.router.navigateByUrl("const?_status="+"OK");
      }
     
    }
   

    if(window.localStorage.Email == 'True'){
      this.tost1("Confirm_Email");
    }
    else if(window.localStorage.Mobile == 'True'){
      this.tost1("Confirm_Mobile");
    }
    else if(window.localStorage.EmailMobile == 'True'){
      this.tost1('EmM');
    }
    else {
    //  window.localStorage.clear();
    //  console.log("Working");
      
   
      // let split1  = testUrl.split('//')[1];
      let split1 = document.URL.split('//')[1];
      console.log('split1',split1);
   
      let split2 = split1.split('.')[1];
      // let split2 = split1.split('/')[1];
     
      
      this.url = split2;
      console.log('this.url',this.url);
  
   
      
      this.dataService.dealerInfo(this.url).subscribe(
        data => {
          this.userData = data 
          console.log(this.userData);
        
       //  this.logo = "http://localhost:3000"+ this.userData.logo;
        this.logo = this.dev_url+this.userData.logo;    
        if(this.url != 'oneqlik'){    
          this.logo_1    =  this.dev_url+this.userData.logo;
          if(this.userData.background_image == undefined) {
            this.backgroundImage = '../../assets/image/login_bg.jpg' ;     
          }else{
            this.backgroundImage = this.dev_url + this.userData.background_image;        
          }    
        }
        
          this.titleServic.setTitle(this.userData.organisationName);
          this.organisationName = (this.url == 'oneqlik')?'OneQlik':this.userData.organisationName  ; 
          this.supportContact = this.userData.contact_support?this.userData.contact_support : ''; 
          this.tagline=  this.userData.tagline?this.userData.tagline : this.tagline;
          this._document.getElementById('appFavicon').setAttribute('href', this.dev_url+this.userData.favicon);
          this.text=this.userData.text;
            window.localStorage['dealerName']= this.userData.dealerName;
            window.localStorage['DealerID'] = this.userData.email
            window.localStorage['DealerPhone'] =this.userData.contactNumber;
            window.localStorage['logo'] =this.logo;
            window.localStorage['text'] = this.text;
            window.localStorage['address'] =this.userData.address;
            window.localStorage['mobile'] = this.userData.contactNumber;
            window.localStorage['facebook'] = this.userData.facebook;
            this.androidAppLink  =this.userData.androidApp ;
            this.iosAppLink = this.userData.appleApp ; 

        },err=>{
          this.backgroundImage = '../../assets/image/login_bg.jpg' ;
       
        }) 

    }
  
    

    history.pushState(null, null, document.URL);
    window.addEventListener('popstate', function () {
        history.pushState(null, null, document.URL);
    });
/*     console.log(this.countDown) 
console.log(--this.count)  */ 

    this.dataService.getdet() .subscribe( logins => this.logins = logins);
 
    for(var i = 0; i <this.showMenu.length;i++){
      if (this.url == this.showMenu[i]) {
        this.showNav = true;
        return;
      } else {
        this.showNav = false;
      }
    }


  }

  forgotpasswordText = "Forgot password ?";
  userForm = new FormGroup({
    email: new FormControl(''),
    password: new FormControl(''),
  });
  forgotpassword(){
    this.hidePassword = !this.hidePassword;
    if(this.hidePassword){
      this.forgotpasswordText = "< Back to login";
      this.buttonText = "Reset password";
    }else{
      this.forgotpasswordText = "Forgot password ?"
      this.buttonText = "Login";
    }
  }
  uservalidate(input) {
    if($(input).attr('type') == 'email' || $(input).attr('name') == 'email') {
        if($(input).val() == null) {
            return false;
        }
    }
    else {
        if($(input).val() == ''){
            return false;
        }
    }
}

showValidate(input) {
  var thisAlert = $(input).parent();
  $(thisAlert).addClass('alert-validate');
}

hideValidate(input) {
  var thisAlert = $(input).parent();

  $(thisAlert).removeClass('alert-validate');
}

catchevent(){
  console.log("Inside function");
}

forgot_passwrord(){
  this.initialLoginForm = !this.initialLoginForm;
  console.log("forgot password clicked");
}
phoneNum:any;
sendOtp(){
  this.resetPasswordTemplate = !this.resetPasswordTemplate;
  console.log(this.phoneNum);
}

backtologin(){
  this.initialLoginForm = true;
  this.resetPasswordTemplate = false;
}

resetPasswordd(){
  console.log('reset password clicked')
}

backtopreviousform(){
  // this.initialLoginForm = !this.initialLoginForm;
  this.resetPasswordTemplate = !this.resetPasswordTemplate;
}

selectedlanguage= 'en';
getLanguage(userid,isOperator,customer_role){
  console.log("KYC APPROVAL--",customer_role);
  
 var Var = { uid: userid };
 this.dataService.getLanguages(Var).subscribe(res=>{
   if (res.language_code=="hi"){
     this.selectedlanguage="en"
   }else{
     this.selectedlanguage = res.language_code ; 

   }
 
   console.log("LNAGHS",res.language_code);
   
  //  iew : "Spanish",
      // id : "sp"
//   },{
//     view : "Persian",
//     id : "fa"
// },{
//   view : "Arabic",
//   id : "ar"
// },{
//   view : "Portuguese",
//   id : "pr"
// },
// {
//   view : "Albanian",
//   id : "newLan2"
  if(this.selectedlanguage != undefined){
    // this.selectedlanguage = this.selectedlanguage;
    // (this.selectedlanguage != ('sp'||'fa'||'pr'||'ar' ||'newLan2'))?'en':this.selectedlanguage;
    console.log("LNAGHS",this.selectedlanguage);
    this.translate.setDefaultLang(this.selectedlanguage);
    this.translate.use(this.selectedlanguage);
   
  }else{
    this.translate.setDefaultLang('en');
    this.translate.use('en');
  
  }
  if(!res.isDealer && !res.isSuperAdmin){
   if(res.show_announcement){
        let dialogRef = this.dialog.open(AnnouncementComponent, {
               width: '550px',
               height: '500px', 
               data:res.announcement  
               
             }); 
            }
      }
  localStorage.setItem('appLang',this.selectedlanguage);
  if(this.urlIdentifier){
    this.router.navigateByUrl("location");
  }else if(isOperator === true){
    this.router.navigateByUrl("Inventorylist");
  }else{
    this.dataService.getImagePath(userid).subscribe(res=>{
      console.log(res);
      var as = res.accountSuspended ; 
      if(as === true){
        this.data_descip =  "Account Suspended , Contact Admin";
        localStorage.clear();
        launch_toast();
      }else{
       
        if(customer_role=="kycApproval"){
          this.router.navigateByUrl("KycApproval");
        }else if(customer_role=="cc"){
         
           this.router.navigateByUrl("reports/notification_master");
        }else{
           this.router.navigateByUrl("const?_status="+"OK");
        }
      }

      function launch_toast() {
        // console.log(divid);
         var x = document.getElementById("toast")
         //console.log(x);
         x.className = "show";
         setTimeout(function(){ x.className = x.className.replace("show", ""); }, 4500);
     }   
    
    })

  }
 },err=>{
   console.log(err);
 })

}
input_type:any= "password";
tooltip_key : any = "Show Password";
showpassword(){
  console.log("Show/Hide Password");
}

rFirst_name :any;
rlast_name:any;
rEmail : any;
rPhone:any; 

requestDemosubmit(){
  console.log("requests for demo");
  console.log({'this.rFirst_name':this.rFirst_name, 'this.rlast_name':this.rlast_name, 'this.rEmail':this.rEmail, 'this.rPhone' : this.rPhone});
  if((this.rFirst_name == undefined)||(this.rEmail == undefined)){
    this.data_descip = "Please Provide Phone and Email address";
    launch_toast();

  }else{
  
    var demoPayload = {
      first_name : this.rFirst_name,
      last_name : this.rlast_name,
      email : this.rEmail,
      phone : this.rPhone,
      url : this.clientUrl
    }
    this.dataService.demorequest(demoPayload).subscribe(res=>{
      console.log(res);
      this.data_descip = "Demo Request Sent";
      launch_toast();
    },err=>{
      console.log(err);
      this.data_descip = "Please Try after sometime";
      launch_toast();
    })
    

  }


  function launch_toast() {
    // console.log(divid);
     var x = document.getElementById("toast")
     //console.log(x);
     x.className = "show";
     setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
 }

}

getADemoReq(){
  this.requestDemo = !this.requestDemo ; 
  if(this.requestDemo == true){
    this.demoString = 'Login';
  }else{
    this.demoString = "Demo Request" ; 
  }
  console.log('this.requestDemo=>',this.requestDemo);
}


gotoShop(){
  console.log('goto shop');
 this.router.navigateByUrl("productShop");
}

}
