import { FormGroup, FormControl, Validators, FormBuilder} from '@angular/forms';
import {ResponseOptions, Response} from '@angular/http';
import {Contact} from '../contact';
import {ContactService} from '../contact.service';
import {Otp} from '../otp';
// import {Md5} from 'ts-md5/dist/md5';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
import { AbstractControl, NG_VALIDATORS, Validator, ValidatorFn } from '@angular/forms';
const EMAIL_REGEX =/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
import { Component, OnInit,Inject } from '@angular/core';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';
import * as moment from 'moment-timezone';
import { ReportService } from '../report/report.service';
declare var google :any;


declare var swal: any,$:any;
@Component({
  selector: 'app-add-cust',
  templateUrl: './add-cust.component.html',
  styleUrls: ['./add-cust.component.scss'],
  providers:[ContactService]
})
export class AddCustComponent implements OnInit {
  superAdmin: any;
  role
  show1:boolean = false;
  show2:boolean = true;
  show3:boolean = false;
  first_name:any=null;
  last_name:any=null;
  passwordd:any=null;
  org_name:any=null;
  emaill:any=null;
  timezone:any = 'Asia/Kolkata';
  phone:any=null;
  executed:any;
  $event2:any;
  dealer:any;
  contacts: Contact[]=[];
  contact: Contact;
  login1:any;
  mess2:any;
  mess:any;
  otp:any;
  userID:any;
  address:any;
  str:boolean = false;
  password2:any=null;
  dealerName:any;
  isTechnician:boolean=false;
  dealerSelect: any=[];
  imageuploadObject = [];
  sup_admin: any;
  countrySelected: {};
  timezoneArray: any[];
  emergencyForm:FormGroup;
  title="ADD CUSTOMER"
  report(){
    this.cond = false
    this.router.navigateByUrl("device-report");
  
  }
  report_speed(){
    // console.log("report speed call")
    this.cond = false
    this.router.navigateByUrl("device-report/device-speed-report");
  }
  stre(){
    this.str =true;
  }
  stren(){
    this.str =false;
  }
  addcus(){
    this.router.navigateByUrl("add");
  }
  clear(){
    this.first_name=' '
    this.last_name=' '
    this.emaill = null
    this.phone = null
  }
  before:any;
  emmnerr:any;
  Load:any
  $event:any;
  constructor(private contactService: ContactService,private router: Router,private _flashMessagesService: FlashMessagesService,public dialogRef: MdDialogRef<AddCustComponent>,private fb:FormBuilder,private reportService:ReportService
    ,@Inject(MD_DIALOG_DATA) public data: any) { 
      console.log("DATATATATA",data);
      if(data){        
        if(data.role=="technitian"){
          this.title="ADD TECHNICIAN";
          this.isTechnician=true;
          this.role=data.role
        }
      }
      var script = document.createElement("script");
      script.setAttribute("type", "text/javascript");
      script.setAttribute("src", "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.0/js/intlTelInput-jquery.min.js");
      document.getElementsByTagName("head")[0].appendChild(script);
    
      var  initialObj = {
        doctype:'',
        image:'',
        phone:''
      }
      this.imageuploadObject.push(initialObj);
    }

  addContact2(){
    console.log(this.router.url);
    var tzone
    if(this.router.url=="/add-device"){
      console.log("in");
      tzone=['Asia/Kolkata']
    this.reportService.addCustomerFunction('')
  }else{

    tzone = $('#dbselect').multipleSelect('getSelects','value'); 
    console.log(tzone);
  }
  //  var tzone
    console.log("EMERGENCY FORM",this.emergencyForm.value);
    
    var expDate = new Date();
    expDate.setFullYear(expDate.getFullYear()+1);
    var countryData = $('#telephone').intlTelInput("getSelectedCountryData");
    console.log(countryData); 
    this.countrySelected = {
      countryCode : countryData.iso2,
      dialcode: countryData.dialCode
    }
    if(this.first_name==null || this.last_name==null || this.passwordd==null )
      {
      return this._flashMessagesService.show('Please fill all Requied fields', { cssClass: 'alert-danger', timeout: 3000 });
       
      }
      // else if((this.userID == undefined)||(this.userID.trim() == '')){
      // return  this._flashMessagesService.show('User ID is required', { cssClass: 'alert-danger', timeout: 3000 });
      // }
      // else if((this.emaill == undefined)||(this.emaill.trim() == '')){

      //  return   this._flashMessagesService.show('Email is mandatory', { cssClass: 'alert-danger', timeout: 3000 });
      // }
      else if(this.password2 != this.passwordd){
       // this._flashMessagesService.show('Password and Confirm Password do not match', { cssClass: 'alert-danger', timeout: 3000 });
        this.tost1("psdnmtch")
       }
      else if (this.emaill && this.phone){
        this.Load=true
        var emergencyContact={
          contact1:{
            name:this.emergencyForm.value.emg_name1,
            cell1:this.emergencyForm.value.emg_cell1,
            cell2:this.emergencyForm.value.emg_cell2,
            phone1:this.emergencyForm.value.emg_phone1,
            phone2:this.emergencyForm.value.emg_phone2

          },
           contact2:{
            name:this.emergencyForm.value.emg_name2,
            cell1:this.emergencyForm.value.emg_cell3,
            cell2:this.emergencyForm.value.emg_cell4,
            phone1:this.emergencyForm.value.emg_phone3,
            phone2:this.emergencyForm.value.emg_phone4

          }
        }
        if(this.dealerObj){   
          this.useridd= this.dealerObj.dealer_id;
          // console.log(this.useridd);
        }
       const newContact2 ={
       first_name: this.first_name,
       last_name: this.last_name,
       email: this.emaill,
       password: this.passwordd,
       phone: this.phone,
       supAdmin:this.sup_admin,
       isDealer: false,
       expdate : new Date(expDate).toISOString(),
       Dealer: this.useridd,
       custumer:true,
       user_id:this.userID,
       address:this.address,
       emergencyContact:emergencyContact
   }
    console.log("1->",newContact2);
   if(this.countrySelected != undefined){
    newContact2['std_code']=this.countrySelected;
   }
   if(tzone != undefined){
    newContact2['timezone'] = tzone[0];
   }
   if(this.role != undefined){
    newContact2['role'] = this.role;
   }

   if(this.imageuploadObject.length > 0){  
     
     for(var d = 0 ;d <this.imageuploadObject.length;d++){
      
       if((this.imageuploadObject[d].doctype == "")&&(this.imageuploadObject[d].image == "")&&(this.imageuploadObject[d].phone == "")){   
             this.imageuploadObject.splice(d,1);         
       }

     }
   }
    console.log("Final DOC ARRAY",this.imageuploadObject);
    newContact2['imageDoc'] = this.imageuploadObject;
    console.log(newContact2);
   this.contactService.addContact(newContact2)
   .subscribe(contact => {   
    if(contact.message == "USER_ID already exists"){
    return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
    }else if(contact.message == "User Duplicate"){
      return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
    }else if(contact.message == "Email ID already exists"){
      return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
    }else if(contact.message == "Mobile Number already exists"){
      return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
    }else{
      this.clear();
      console.log(contact);
     //  USER_ID already exists
      this.Load=false
       if(this.router.url!="/add-device"){

         this.onNoClick("succ");
         this.contacts.push(contact);
       }else{
         this._flashMessagesService.show(contact.message, { cssClass: 'alert-success', timeout: 3000 });
       }
    }
 
   }, (err: any) => { 
    // console.log(err.status); 
    console.log(err);
  if(err.status ==  500)
  {
    this.Load=false
    this.emmnerr=JSON.parse(err._body);
    console.log(this.emmnerr);
    this.data_descip = this.emmnerr.split(':')[1];
    console.log(this.data_descip);
     this._flashMessagesService.show(this.data_descip, { cssClass: 'alert-danger', timeout: 3000 });
    // swal(
    //   'Error',
    //   this.data_descip,
    //   'error'
    // )
  }
  else if(err.status==401){
    this.Load=false;
    this.emmnerr=JSON.parse(err._body);
    console.log(this.emmnerr);
    this.data_descip = this.emmnerr.message

     this._flashMessagesService.show("Access Denied", { cssClass: 'alert-danger', timeout: 3000 });
    // swal(
    //   'Error',
    //   'Internal Server error , Please try after sometime !!!',
    //   'error'
    // )

  }else{
    this.Load=false;
     this._flashMessagesService.show("Internal Server Error, Please try after sometime !!!", { cssClass: 'alert-danger', timeout: 3000 });
  }
  });

 }
      else if(this.phone){
        this.Load=true
        if(this.dealerObj){
          this.useridd= this.dealerObj.dealer_id;
        }
         var emergencyContact={
          contact1:{
            name:this.emergencyForm.value.emg_name1,
            cell1:this.emergencyForm.value.emg_cell1,
            cell2:this.emergencyForm.value.emg_cell2,
            phone1:this.emergencyForm.value.emg_phone1,
            phone2:this.emergencyForm.value.emg_phone2

          },
           contact2:{
            name:this.emergencyForm.value.emg_name2,
            cell1:this.emergencyForm.value.emg_cell3,
            cell2:this.emergencyForm.value.emg_cell4,
            phone1:this.emergencyForm.value.emg_phone3,
            phone2:this.emergencyForm.value.emg_phone4

          }
        }

    //   if (!this.executed) {
    //     this.executed = true;
         const newContact2 ={
         first_name: this.first_name,
         last_name: this.last_name,
         password: this.passwordd,
         supAdmin:this.sup_admin,
         expdate : new Date(expDate).toISOString(),
         phone: this.phone,
         isDealer: false,
         Dealer: this.useridd,
         custumer:true,
         user_id:this.userID,
         address:this.address,
         emergencyContact:emergencyContact
     }
console.log("2->",newContact2);

     
   if(this.countrySelected != undefined){
    newContact2['std_code']=this.countrySelected;
   }
   if(this.role != undefined){
    newContact2['role'] = this.role;
   }

   if(tzone != undefined){
    newContact2['timezone'] = tzone[0];
   }

     if(this.imageuploadObject.length > 0){  

      for(var d = 0 ;d <this.imageuploadObject.length;d++){   
        if((this.imageuploadObject[d].doctype == "")&&(this.imageuploadObject[d].image == "")&&(this.imageuploadObject[d].phone == "")){   
              this.imageuploadObject.splice(d,1);        
        }
      }
    }
    newContact2['imageDoc'] = this.imageuploadObject;
     this.contactService.addContact(newContact2)
     .subscribe(contact => {
      console.log(contact);
      if(contact.message == "USER_ID already exists"){
        return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
        }else if(contact.message == "User Duplicate"){
          return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
        }else if(contact.message == "Email ID already exists"){
          return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
        }else if(contact.message == "Mobile Number already exists"){
          return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
        }else{
          this.clear();
          this.Load=false;
           if(this.router.url!="/add-device"){

         this.onNoClick("succ");
         this.contacts.push(contact);
       }else{
         this._flashMessagesService.show(contact.message, { cssClass: 'alert-success', timeout: 3000 });
       }
         
        }
      //  USER_ID already exists
   
     }, (err: any) => {
    if(err.status ==  500)
    {
    //  console.log(err._body);
      this.Load=false
      this.emmnerr=JSON.parse(err._body);
        console.log(this.emmnerr);
       this.data_descip = this.emmnerr.split(':')[1];
        console.log(this.data_descip);
         this._flashMessagesService.show(this.data_descip, { cssClass: 'alert-danger', timeout: 3000 });
    // swal(
    //   'Error',
    //   this.data_descip,
    //   'error'
    // )
    }
    else if(err.status==401){

      this.Load=false;
       this.emmnerr=JSON.parse(err._body);
        console.log(this.emmnerr);
       this.data_descip = this.emmnerr.message
      // console.log("dadsa");
      this._flashMessagesService.show("Access Denied", { cssClass: 'alert-danger', timeout: 3000 });
    }else{
       this._flashMessagesService.show("Internal Server Error, Please try after sometime", { cssClass: 'alert-danger', timeout: 3000 });
    }})}
 else if((this.emaill)||(this.userID)){
 // if (!this.executed) {
  //  this.executed = true;
    console.log("we are here");
  if(this.dealerObj){
    this.useridd= this.dealerObj.dealer_id
    
  }
  var emergencyContact={
       contact1:{
         name:this.emergencyForm.value.emg_name1,
         cell1:this.emergencyForm.value.emg_cell1,
         cell2:this.emergencyForm.value.emg_cell2,
         phone1:this.emergencyForm.value.emg_phone1,
         phone2:this.emergencyForm.value.emg_phone2

       },
        contact2:{
         name:this.emergencyForm.value.emg_name2,
         cell1:this.emergencyForm.value.emg_cell3,
         cell2:this.emergencyForm.value.emg_cell4,
         phone1:this.emergencyForm.value.emg_phone3,
         phone2:this.emergencyForm.value.emg_phone4

       }
     }
     console.log(emergencyContact);
     
    const newContact2 ={
    first_name: this.first_name,
    last_name: this.last_name,
    password: this.passwordd,
    org_name: this.org_name,
    email: this.emaill,
    expdate : new Date(expDate).toISOString(),
    supAdmin:this.sup_admin,
    isDealer: false,
    Dealer: this.useridd,
    custumer:true,
    user_id:this.userID,
    address:this.address,
    emergencyContact:emergencyContact

}
console.log("3->",newContact2);


if(this.countrySelected != undefined){
  newContact2['std_code']=this.countrySelected;

 }
 if(this.role != undefined){
    newContact2['role'] = this.role;
   }

 if(tzone != undefined){
  newContact2['timezone'] = tzone[0];
 }

if(this.imageuploadObject.length > 0){  

  for(var d = 0 ;d <this.imageuploadObject.length;d++){
    if((this.imageuploadObject[d].doctype == "")&&(this.imageuploadObject[d].image == "")&&(this.imageuploadObject[d].phone == "")){   
          this.imageuploadObject.splice(d,1);   
    }
  }
}
newContact2['imageDoc'] = this.imageuploadObject;
this.contactService.addContact(newContact2)
.subscribe(contact => {
  //this.tost1("succ")
  console.log(contact);
  //  USER_ID already exists
  if(contact.message == "USER_ID already exists"){
    return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
    }if(contact.message == "USER_ID already exists"){
      return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
      }else if(contact.message == "User Duplicate"){
        return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
      }else if(contact.message == "Email ID already exists"){
        return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
      }else if(contact.message == "Mobile Number already exists"){
        return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
      }else{
      this.clear();
      this.Load=false
       if(this.router.url!="/add-device"){

         this.onNoClick("succ");
         this.contacts.push(contact);
       }else{
         this._flashMessagesService.show(contact.message, { cssClass: 'alert-success', timeout: 3000 });
       }
      
    }
 
}, (err: any) => {
  console.log();
  
  if(err.status ==  500)
  {
  //  console.log(err._body);
    this.Load=false
    this.emmnerr=JSON.parse(err._body);
  
    this.data_descip = this.emmnerr.split(':')[1];
    console.log(this.data_descip);
    this._flashMessagesService.show(this.data_descip, { cssClass: 'alert-danger', timeout: 3000 });
    // swal(
    //   'Error',
    //   this.data_descip,
    //   'error'
    // )
    // console.log("error to display",this.emmnerr);
    // this.tost1("Error")
  }
  else if(err.status ==  401){
    this.Load=false;
    this._flashMessagesService.show("Access Denied", { cssClass: 'alert-danger', timeout: 3000 });
    //  this.emmnerr=JSON.parse(err._body);
    // swal(
    //   'Error',
    //   this.emmnerr.message,
    //   'error'
    // )
  }else{
     this.Load=false;
     this._flashMessagesService.show("Internal Server Error, Please try again sometime !!", { cssClass: 'alert-danger', timeout: 3000 });
    //  this.emmnerr=JSON.parse(err._body);
    // swal(
    //   'Error',
    //   this.emmnerr.message,
    //   'error'
    // )
  }
});


 }
 
 
 }

 addContact3(){

 var tzone
    if(this.router.url=="/add-device"){
      console.log("in");
      tzone=['Asia/Kolkata']
    this.reportService.addCustomerFunction('')
  }else{

    tzone = $('#dbselect').multipleSelect('getSelects','value'); 
    console.log(tzone);
  }

    // var tzone = $('#dbselect').multipleSelect('getSelects','value'); 
    // console.log(tzone);
    console.log("EMERGENCY FORM",this.emergencyForm.value);
    
    var expDate = new Date();
    expDate.setFullYear(expDate.getFullYear()+1);
    var countryData = $('#telephone').intlTelInput("getSelectedCountryData");
    console.log(countryData); 
    this.countrySelected = {
      countryCode : countryData.iso2,
      dialcode: countryData.dialCode
    }
    if(this.first_name==null || this.last_name==null || this.passwordd==null )
      {
      return this._flashMessagesService.show('Please fill all Requied fields', { cssClass: 'alert-danger', timeout: 3000 });
       
      }
      // else if((this.userID == undefined)||(this.userID.trim() == '')){
      // return  this._flashMessagesService.show('User ID is required', { cssClass: 'alert-danger', timeout: 3000 });
      // }
      // else if((this.emaill == undefined)||(this.emaill.trim() == '')){

      //  return   this._flashMessagesService.show('Email is mandatory', { cssClass: 'alert-danger', timeout: 3000 });
      // }
      else if(this.password2 != this.passwordd){
       // this._flashMessagesService.show('Password and Confirm Password do not match', { cssClass: 'alert-danger', timeout: 3000 });
        this.tost1("psdnmtch")
       }
      else if (this.emaill && this.phone){
        this.Load=true
        var emergencyContact={
          contact1:{
            name:this.emergencyForm.value.emg_name1,
            cell1:this.emergencyForm.value.emg_cell1,
            cell2:this.emergencyForm.value.emg_cell2,
            phone1:this.emergencyForm.value.emg_phone1,
            phone2:this.emergencyForm.value.emg_phone2

          },
           contact2:{
            name:this.emergencyForm.value.emg_name2,
            cell1:this.emergencyForm.value.emg_cell3,
            cell2:this.emergencyForm.value.emg_cell4,
            phone1:this.emergencyForm.value.emg_phone3,
            phone2:this.emergencyForm.value.emg_phone4

          }
        }
        if(this.dealerObj){   
          this.useridd= this.dealerObj.dealer_id;
          // console.log(this.useridd);
        }
       const newContact2 ={
       first_name: this.first_name,
       last_name: this.last_name,
       email: this.emaill,
       password: this.passwordd,
       phone: this.phone,
       supAdmin:this.sup_admin,
       isDealer: false,
       expdate : new Date(expDate).toISOString(),
       Dealer: this.useridd,
       custumer:true,
       user_id:this.userID,
       address:this.address,
       emergencyContact:emergencyContact
   }
    console.log("1->",newContact2);
   if(this.countrySelected != undefined){
    newContact2['std_code']=this.countrySelected;
   }
   if(tzone != undefined){
    newContact2['timezone'] = tzone[0];
   }
   if(this.role != undefined){
    newContact2['role'] = this.role;
   }

   if(this.imageuploadObject.length > 0){  
     
     for(var d = 0 ;d <this.imageuploadObject.length;d++){
      
       if((this.imageuploadObject[d].doctype == "")&&(this.imageuploadObject[d].image == "")&&(this.imageuploadObject[d].phone == "")){   
             this.imageuploadObject.splice(d,1);         
       }

     }
   }
    console.log("Final DOC ARRAY",this.imageuploadObject);
    newContact2['imageDoc'] = this.imageuploadObject;
    console.log(newContact2);
   this.contactService.post('/users/addTechnician',newContact2)
   .subscribe((contact:any) => {   
    if(contact.message == "USER_ID already exists"){
    return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
    }else if(contact.message == "User Duplicate"){
      return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
    }else if(contact.message == "Email ID already exists"){
      return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
    }else if(contact.message == "Mobile Number already exists"){
      return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
    }else{
      this.clear();
      console.log(contact);
     //  USER_ID already exists
      this.Load=false
       if(this.router.url!="/add-device"){

         this.onNoClick("succ");
         this.contacts.push(contact);
       }else{
         this._flashMessagesService.show(contact.message, { cssClass: 'alert-success', timeout: 3000 });
       }
      // this.onNoClick("succ");
      // this.contacts.push(contact);
    }
 
   }, (err: any) => { 
    // console.log(err.status); 
    console.log(err);
  if(err.status ==  500)
  {
    this.Load=false
    this.emmnerr=JSON.parse(err._body);
    console.log(this.emmnerr);
    this.data_descip = this.emmnerr.split(':')[1];
    console.log(this.data_descip);
     this._flashMessagesService.show(this.data_descip, { cssClass: 'alert-danger', timeout: 3000 });
    // swal(
    //   'Error',
    //   this.data_descip,
    //   'error'
    // )
  }
  else if(err.status==401){
    this.Load=false
     this.Load=false
    this.emmnerr=JSON.parse(err._body);
    console.log(this.emmnerr);
    this.data_descip = this.emmnerr.message;
    this._flashMessagesService.show("Access Denied", { cssClass: 'alert-danger', timeout: 3000 });
    // swal(
    //   'Error',
    //   'Internal Server error , Please try after sometime !!!',
    //   'error'
    // )

  }else{
    this.Load=false
    swal(
      'Error',
      'Internal Server error , Please try after sometime !!!',
      'error'
    )
  }
  });

 }
      else if(this.phone){
        this.Load=true
        if(this.dealerObj){
          this.useridd= this.dealerObj.dealer_id;
        }
         var emergencyContact={
          contact1:{
            name:this.emergencyForm.value.emg_name1,
            cell1:this.emergencyForm.value.emg_cell1,
            cell2:this.emergencyForm.value.emg_cell2,
            phone1:this.emergencyForm.value.emg_phone1,
            phone2:this.emergencyForm.value.emg_phone2

          },
           contact2:{
            name:this.emergencyForm.value.emg_name2,
            cell1:this.emergencyForm.value.emg_cell3,
            cell2:this.emergencyForm.value.emg_cell4,
            phone1:this.emergencyForm.value.emg_phone3,
            phone2:this.emergencyForm.value.emg_phone4

          }
        }

    //   if (!this.executed) {
    //     this.executed = true;
         const newContact2 ={
         first_name: this.first_name,
         last_name: this.last_name,
         password: this.passwordd,
         supAdmin:this.sup_admin,
         expdate : new Date(expDate).toISOString(),
         phone: this.phone,
         isDealer: false,
         Dealer: this.useridd,
         custumer:true,
         user_id:this.userID,
         address:this.address,
         emergencyContact:emergencyContact
     }
console.log("2->",newContact2);

     
   if(this.countrySelected != undefined){
    newContact2['std_code']=this.countrySelected;
   }
   if(this.role != undefined){
    newContact2['role'] = this.role;
   }

   if(tzone != undefined){
    newContact2['timezone'] = tzone[0];
   }

     if(this.imageuploadObject.length > 0){  

      for(var d = 0 ;d <this.imageuploadObject.length;d++){   
        if((this.imageuploadObject[d].doctype == "")&&(this.imageuploadObject[d].image == "")&&(this.imageuploadObject[d].phone == "")){   
              this.imageuploadObject.splice(d,1);        
        }
      }
    }
    newContact2['imageDoc'] = this.imageuploadObject;
     this.contactService.post('/users/addTechnician',newContact2)
     .subscribe((contact:any) => {
      console.log(contact);
      if(contact.message == "USER_ID already exists"){
        return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
        }else if(contact.message == "User Duplicate"){
          return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
        }else if(contact.message == "Email ID already exists"){
          return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
        }else if(contact.message == "Mobile Number already exists"){
          return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
        }else{
          this.clear();
          this.Load=false;
           if(this.router.url!="/add-device"){

         this.onNoClick("succ");
         this.contacts.push(contact);
       }else{
         this._flashMessagesService.show(contact.message, { cssClass: 'alert-success', timeout: 3000 });
       }
          // this.onNoClick("succ");
          //  this.contacts.push(contact);
        }
      //  USER_ID already exists
   
     }, (err: any) => {
    if(err.status ==  500)
    {
    //  console.log(err._body);
      this.Load=false
      this.emmnerr=JSON.parse(err._body);
        console.log(this.emmnerr);
       this.data_descip = this.emmnerr.split(':')[1];
        console.log(this.data_descip);
    swal(
      'Error',
      this.data_descip,
      'error'
    )
    }
    else if(err.status==401){
      this.Load=false
     this.emmnerr=JSON.parse(err._body);
        console.log(this.emmnerr);
       this.data_descip = this.emmnerr.message;
        this._flashMessagesService.show("Access Denied", { cssClass: 'alert-danger', timeout: 3000 });
      // swal(
      //   'Error',
      //   'Internal Server error , Please try after sometime !!!',
      //   'error'
      // )
    }else{
        this.Load=false;
        this._flashMessagesService.show('Internal Server error , Please try after sometime !!!', { cssClass: 'alert-danger', timeout: 3000 });
    }
  })}
 else if((this.emaill)||(this.userID)){
 // if (!this.executed) {
  //  this.executed = true;
    console.log("we are here");
  if(this.dealerObj){
    this.useridd= this.dealerObj.dealer_id
    
  }
  var emergencyContact={
       contact1:{
         name:this.emergencyForm.value.emg_name1,
         cell1:this.emergencyForm.value.emg_cell1,
         cell2:this.emergencyForm.value.emg_cell2,
         phone1:this.emergencyForm.value.emg_phone1,
         phone2:this.emergencyForm.value.emg_phone2

       },
        contact2:{
         name:this.emergencyForm.value.emg_name2,
         cell1:this.emergencyForm.value.emg_cell3,
         cell2:this.emergencyForm.value.emg_cell4,
         phone1:this.emergencyForm.value.emg_phone3,
         phone2:this.emergencyForm.value.emg_phone4

       }
     }
     console.log(emergencyContact);
     
    const newContact2 ={
    first_name: this.first_name,
    last_name: this.last_name,
    password: this.passwordd,
    org_name: this.org_name,
    email: this.emaill,
    expdate : new Date(expDate).toISOString(),
    supAdmin:this.sup_admin,
    isDealer: false,
    Dealer: this.useridd,
    custumer:true,
    user_id:this.userID,
    address:this.address,
    emergencyContact:emergencyContact

}
console.log("3->",newContact2);


if(this.countrySelected != undefined){
  newContact2['std_code']=this.countrySelected;

 }
 if(this.role != undefined){
    newContact2['role'] = this.role;
   }

 if(tzone != undefined){
  newContact2['timezone'] = tzone[0];
 }

if(this.imageuploadObject.length > 0){  

  for(var d = 0 ;d <this.imageuploadObject.length;d++){
    if((this.imageuploadObject[d].doctype == "")&&(this.imageuploadObject[d].image == "")&&(this.imageuploadObject[d].phone == "")){   
          this.imageuploadObject.splice(d,1);   
    }
  }
}
newContact2['imageDoc'] = this.imageuploadObject;
this.contactService.post('/users/addTechnician',newContact2)
.subscribe((contact:any) => {
  //this.tost1("succ")
  console.log(contact);
  //  USER_ID already exists
  if(contact.message == "USER_ID already exists"){
    return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
    }if(contact.message == "USER_ID already exists"){
      return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
      }else if(contact.message == "User Duplicate"){
        return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
      }else if(contact.message == "Email ID already exists"){
        return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
      }else if(contact.message == "Mobile Number already exists"){
        return  this._flashMessagesService.show(contact.message, { cssClass: 'alert-danger', timeout: 3000 });
      }else{
      this.clear();
      this.Load=false;
       if(this.router.url!="/add-device"){

         this.onNoClick("succ");
         this.contacts.push(contact);
       }else{
         this._flashMessagesService.show(contact.message, { cssClass: 'alert-success', timeout: 3000 });
       }
      // this.onNoClick("succ");
      // this.contacts.push(contact);
    }
 
}, (err: any) => {
  if(err.status ==  500)
  {
  //  console.log(err._body);
    this.Load=false
    this.emmnerr=JSON.parse(err._body);
  
    this.data_descip = this.emmnerr.split(':')[1];
    console.log(this.data_descip);
     this._flashMessagesService.show(this.data_descip, { cssClass: 'alert-danger', timeout: 3000 });
    // swal(
    //   'Error',
    //   this.data_descip,
    //   'error'
    // )
    // console.log("error to display",this.emmnerr);
    // this.tost1("Error")
  }
  else if(err.status==401){
    this.Load=false;
    this.emmnerr=JSON.parse(err._body);
    this.data_descip = this.emmnerr.message;
    this._flashMessagesService.show("Access Denied", { cssClass: 'alert-danger', timeout: 3000 });
    // swal(
    //   'Error',
    //   'Internal Server error , Please try after sometime !!!',
    //   'error'
    // )
  }else{
     this.Load=false;
    this._flashMessagesService.show( 'Internal Server error , Please try after sometime !!!', { cssClass: 'alert-danger', timeout: 3000 });
  }});


 }
 
 
 }
 data_descip:any;
 onNoClick(a): void {
  this.dialogRef.close(a);
 }

 closebox(){
  this.dialogRef.close(null);
 }
 tost1(divid){
  if(divid == "Error"){
     this.data_descip = "User already registerd"
     this._flashMessagesService.show(this.data_descip, { cssClass: 'alert-danger', timeout: 3000 });
   }
   else if(divid == "succ"){
     this.data_descip = "Custumer Successfully Added"
     this._flashMessagesService.show("Custumer Successfully Added", { cssClass: 'alert-success', timeout: 3000 });
   }
   else if(divid == "psdnmtch"){
    this.data_descip =  "Error: Password and confirm password do not match"
    this._flashMessagesService.show(this.data_descip, { cssClass: 'alert-danger', timeout: 3000 });
   }
  //    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", ""); }, 450000);
  //  }
    }

  valclear(){
    this._flashMessagesService.show("Cleared", { cssClass: 'alert-warning', timeout: 200000 });        
    
  }

  click1(event){
    this.show2=false;
    this.show3=true;
    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();
    }
    click2(event2){
      this.show2=true;
      this.show3=false;
      
      }
      call(e) {
        {
               if (e.keyCode == 32) {
                   e.preventDefault();
               }
           }
   }
   geo(){
    this.router.navigateByUrl("geofencing");
    
  }
  devicess:any;
  final:any;
  getdev(){
    let foods = []
    this.contactService.getDevice(this.emailid,this.useridd).subscribe(
        
      data => {
        this.devicess = data 
  
        let swap;
        for(let g = 0;g<this.devicess.devices.length-1;g++ ){
          for(let c = 0;c<this.devicess.devices.length-g-1;c++ ){
            if(this.devicess.devices[c].Device_Name>this.devicess.devices[c+1].Device_Name){
                swap = this.devicess.devices[c];
                this.devicess.devices[c] = this.devicess.devices[c+1];
                this.devicess.devices[c+1] = swap;
            }
          }
        }
  
        this.final = this.devicess.devices
        
       for(let i=0;i<this.devicess.devices.length;i++){
       
        //  if(this.devicess.devices[i].type_of_device =="Tracker"){
           let a ={
            value : this.devicess.devices[i].Device_Name,
            viewValue:this.devicess.devices[i].Device_Name
           }
           foods.push(a);
        //  }
      
       }
  
      });
  }
  cond:Boolean = false;
  point : any = 0;
  aa(){
    // console.log(this.point);
     if(this.point == 0){
      this.cond = true;
      this.point ++;
     }
   else if(this.point % 2 == 0){
    this.cond = true;
    this.point ++;
   }
   else{
     this.cond = false
     this.point ++;
   }
  
    
  }
run(){

}
openNav() {
  /*  document.getElementById("myNav").style.width = "100%";
*/
   this.router.navigateByUrl("location");

}
   logout(){
    window.localStorage.clear();
    this.router.navigateByUrl("login");
  }
  devi(){
    this.router.navigateByUrl("dashboard");

  }
  ideal(){
    this.router.navigateByUrl("device-report/ideal-report");
  }
  soon(){
    this.router.navigateByUrl("const?_i="+window.localStorage.token);
    
  }
  new(){
    this.router.navigateByUrl("new");
    
  }
   fs:any;
   ls:any;
   emailid:any;
   or:any;
   useridd:any;
   custtype:any;
   cust:boolean=false;
   mb:any;
   logo:any;
   text:any;
  ngOnInit() {

    this.emergencyForm=this.fb.group({
      emg_name1:[''],
      emg_name2:[''],
      emg_cell1:[''],
      emg_cell2:[''],
      emg_cell3:[''],
      emg_cell4:[''],
      emg_phone1:[''],
      emg_phone2:[''],
      emg_phone3:[''],
      emg_phone4:['']

    })
      setTimeout(() => {
        $("#telephone").intlTelInput({
          allowDropdown:true,
          autoPlaceholder:"Enter Mobile Number",
          initialCountry:"in",
          preferredCountries: ["in","us" ],
          separateDialCode:true,
          }); 
      }, 300);
      
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    // console.log(this.superAdmin)
    this.fs = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).fn;
    this.ls = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).ln;
    if(!this.superAdmin){
      this.dealerName = this.fs
    }
    this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
    this.or = JSON.parse(window.atob(window.localStorage.token.split(".")[1]))._orgName;
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.mb =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).phn;

    this.custtype =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;

    this.sup_admin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).supAdmin;
    console.log("superAdmin=>",this.sup_admin);

    if(this.superAdmin){
      this.sup_admin = this.useridd;
    }

  //  this.getdev();
  if(this.mb.charAt(0)=="n"){
    this.mb = ' '
  }
  if(this.custtype == true){
    this.cust = true;
  }

  this.logo=window.localStorage['logo'];
  this.text=window.localStorage['text'];  
  this.dealerDetail();
  
  var Phoneinput = document.getElementById('telephone');
  var that = this;
  Phoneinput.addEventListener("countrychange",function(p) {
    console.log("Inside Function");
    var countryData = $('#telephone').intlTelInput("getSelectedCountryData");
    console.log(countryData); 
    that.countrySelected = {
      countryCode : countryData.iso2,
      dialcode: countryData.dialCode
    }
    });

    var timeZn = moment.tz.guess(); 
    if(timeZn != 'Asia/Calcutta'){
      this.timezone = timeZn;
    }
    console.log(this.timezone);


  var timeZones = moment.tz.names();
  console.log(timeZones);
  this.timezoneArray=[];
  for (var i in timeZones) {
    this.timezoneArray.push({ viewValue: "(GMT" + moment.tz(timeZones[i]).format('Z') + ")" + timeZones[i], value: timeZones[i] });
  }
  

  setTimeout(() => {
    $('#dbselect').multipleSelect({
      width: 300,
      placeholder: 'Select Timezone',
      filter: true,
      single: true,
      selectAll: false
    })   
    console.log("INBDKJNDKJNDKJFNKJFBKHJbnkjh");
    
  }, 100);

  this.latLongDetail();
  }

  dealers_info=[];

  dealerDetail(){
    // this.dealers_info=[];
    var super_admin = ((this.superAdmin==true)||(this.superAdmin==undefined)) ? this.useridd : this.sup_admin ; 
    this.contactService.dealer_Info_dealer_list(super_admin)
    .subscribe(res=>{
      console.log("Response=>",res);
      this.dealers_info=res;
    })
    

  }


  filterDealerStates(dlr) {

    // console.log(dlr);
    if (dlr) {

      const filterdealerValue:any = dlr;
      this.dealerSelect=[];
       this.dealerSelect = this.dealers_info.filter(function(p){
        var t = p.dealer_firstname.toLocaleLowerCase().indexOf(filterdealerValue.toLocaleLowerCase());
      //  this.option = this.options[i];
    
     
        return t > -1;    
      });
      
        return this.dealerSelect;
    }
  
  }

  dealerObj:any;
  dealerFinalVal(dlrr){

    
    this.dealerObj=dlrr;
    // console.log(this.dealerObj);

    // this.dealerSelect = dlrr;
    // console.log(this.dealerSelect);

  }
  documentDetail:any;
  imageURL:any;

  documentList = [
    {
      "docId": "Adhar",
      "docName": "Adhar Card"
    },
    {
      "docId": "voterCard",
      "docName": "Voter Id"
    },
    {
      "docId": "PAN",
      "docName": "Pan Card"
    },
    {
      "docId": "DL",
      "docName": "Driving License"
    },
    {
      "docId": "Nepali Citizenship",
      "docName": "Nepali Citizenship"
    }
    
  ];

  documentType(docType){
    console.log("doctypeObject=>",docType);

  }
  selectedFile: File;
  onFileChanged(event) { 
    this.selectedFile = <File>event.target.files[0];
    console.log(this.selectedFile); 
  }

  onUpload(imgIndex) {
    console.log(imgIndex);
    console.log(this.imageuploadObject);
    const fd = new FormData();
    console.log("selected file name =>",this.selectedFile.name);
    if(this.selectedFile.name == " "){
      swal(
        'Upload Error',
        'Please select document type before upload !!!',
        'error'
      )
    }else{
      fd.append('photo',this.selectedFile,this.selectedFile.name)
      console.log("imgURL=>",fd) ;
      this.contactService.imageupload(fd)
      .subscribe(res=>{
        console.log(res);
        var resImage ='';
        resImage = res['_body'];
        console.log(res['_body']);
        this.imageuploadObject[imgIndex].image = resImage;
         console.log(this.imageuploadObject);
        // console.log(res);
      },err=>{
        swal(
          'Server Error',
          'Internal Server Error , plaese try after sometime !!!',
          'error'
        )
      })
    }
   }

   docRow:boolean=false;;
  AddDocumentsField(addedRow){
      if(addedRow){
        this.docRow = true;
      }
       var obj={doctype:'',image:'',phone:''};
       this.imageuploadObject.push(obj);
       console.log(this.imageuploadObject);
      // console.log("ImageuploadObject=>",this.imageuploadObject);
  }

  DeleteDocumentsField(index){
    console.log(this.imageuploadObject.length);
    if(this.imageuploadObject.length == 1){
      this.docRow = false;
    }
    this.imageuploadObject.splice(index, 1);

  }
  passwordtype:any= 'password';
  passwordtype_1:any= 'password';
  passwordIcon:any='visibility_off';
  passwordIcon_1:any='visibility_off';

  showpassword(p:any){
    console.log('inside function');
   
    if((p == 'p1')&&(this.passwordtype == "password")){
      this.passwordtype = 'text';
      this.passwordIcon = 'visibility';
      return
 
    }
 
    if((p == 'p1')&&(this.passwordtype == "text")){
      this.passwordtype = 'password';
      this.passwordIcon = 'visibility_off';
      return;
    }
 
    if((p == 'p2')&&(this.passwordtype_1 == "password")){
     this.passwordtype_1 = 'text';
     this.passwordIcon_1 = 'visibility';
     return;
 
   }
 
   if((p == 'p2')&&(this.passwordtype_1 == "text")){
     this.passwordtype_1 = 'password';
     this.passwordIcon_1 = 'visibility_off';
     return;
   }
 
  }
  

  latLongDetail(){
    var that =this;
    console.log("Inside Latlong Function");
    if (navigator.geolocation) {  
   
      if(location.protocol != 'https:'){
        this.contactService.getlatLong().subscribe(res=>{
          console.log(res); 
            let t_latlng = new google.maps.LatLng(res.lat, res.lon);
            let request = {
              latLng: t_latlng
            };

          this.getAddress(request);
        })
      }else{
        navigator.geolocation.getCurrentPosition(function(position) {
          var d_lat= position.coords.latitude;
          var d_lng=position.coords.longitude;
          let t_latlng = new google.maps.LatLng(d_lat, d_lng);
          let request = {
            latLng: t_latlng
          };

          that.getAddress(request);
        })
        
      }}            
  }

  getAddress(request){ 
    let geocoder = new google.maps.Geocoder();  
    geocoder.geocode(request, function (data, status) {
      console.log("Inside geocoder function");  
      var userCountry;
      if (status == google.maps.GeocoderStatus.OK) {
        if (data[0] != null) {
          var address_show = data[0];
          console.log('var=>' ,address_show);
          for (var ac = 0; ac < data[0].address_components.length; ac++) {
            var component = data[0].address_components[ac];
            switch(component.types[0]) {     
                case 'country':
                    userCountry  = component.short_name;
                    console.log(userCountry);
                    break;      
            }
        };
         
            var aaa = $('#telephone').intlTelInput("setCountry",userCountry);
        } else {
          userCountry = 'in';  
        }
      }
      else {
        console.log("Inside Error function");  
        userCountry = 'in';
      }
    })  
  }
}
