import { Component, OnInit, ViewChild, Input, } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MdSnackBar } from '@angular/material';

import {ContactService} from '../contact.service';
 

declare var google: any,swal: any;
@Component({
  selector: 'app-user-finder',
  templateUrl: './user-finder.component.html',
  styleUrls: ['./user-finder.component.scss']
})
export class UserFinderComponent implements OnInit {
 emailId: any;
  searchForm:FormGroup;
  deleteShow:boolean=false;
   submitted = false;
  userId: any;
  deviceForm:FormGroup
  data: any;
  deleted:boolean=false;
  // @ViewChild(BaseChartDirective) public chart: BaseChartDirective;
  constructor(private contactService:ContactService,private fb:FormBuilder,public snackBar: MdSnackBar){
    
    }
  ngOnInit(): void {
    this.searchForm=this.fb.group({
      imei:['',Validators.required]
    })

//  Name
//  emial
//  dealer
//  superadmin
//  isdeleted
//  issuspended
//  user id
//  createdon
//  expiredon

    this.deviceForm=this.fb.group({
      Name:[''],
      email:[''],
      Dealer:[''],
      supAdmin:[''],
      accountSuspended:[''],
      user_id:[''],
      created_on:[''],
      expire_date:[''],
      DeletedUser:['']
      // imei:[''],
      // registrationNumber:[''],
      // sim1:[''],
      // sim2:[''],
      // dealaer:[''],
      // user:[''],
      // deviceModel:[''],
      // vehicleType:[''],
      // expirationDate:[''],
      // creationDate:[''],
      // superAdmin:[''],
      // lastRenewal:[''],
      // status:[''],
      // deleted:[''],
      // deletedBy:[''],
      // deletedAt:[''],
      // deletedFrom:['']

// 352887076587769
    })
     this.emailId = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
    this.userId = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
  }
  
 get f() { return this.searchForm.controls; }

  submit(){
    console.log(this.searchForm.value);
    
      this.submitted = true;

        // stop here if form is invalid
        if (this.searchForm.invalid) {
            return;
        }
        this.contactService.get('/users/searchUser?search='+this.searchForm.value.imei).subscribe((res:any)=>{
          console.log(res);
          this.data=res[0];
          if(res.length!=0){
            this.deleteShow=true
            if(res[0].DeletedUser){
              this.deleteShow=false;
              this.deleted=true;
            }else{

              this.deleted=false;
            }
            console.log(res[0].Dealer?res[0].Dealer.last_name?res[0].Dealer.last_name:"":'');
            var dealerFirst=res[0].Dealer?res[0].Dealer.first_name?res[0].Dealer.first_name:'':'';
            var dealerLast=res[0].Dealer?res[0].Dealer.last_name?res[0].Dealer.last_name:"":''
            var supFirst=res[0].supAdmin?res[0].supAdmin.first_name?res[0].supAdmin.first_name:'':''
            var supLast=res[0].supAdmin?res[0].supAdmin.last_name?res[0].supAdmin.last_name:'':''
            // var dealer=res[0].Dealer?res[0].Dealer.first_name?res[0].Dealer.first_name:'':''+' '+res[0].Dealer?res[0].Dealer.last_name?res[0].Dealer.last_name:"":''
            // var supAdm=res[0].supAdmin?res[0].supAdmin.first_name?res[0].supAdmin.first_name:'':''+' '+res[0].supAdmin?res[0].supAdmin.last_name?res[0].supAdmin.last_name:'':''
            this.deviceForm.patchValue({
              Name:[res[0].first_name?res[0].first_name:''+' '+res[0].last_name?res[0].last_name:''],
              email:[res[0].email],
              Dealer:[dealerFirst+" "+dealerLast],
              supAdmin:[supFirst+' '+supLast],
              accountSuspended:[res[0].accountSuspended==true?'Yes':'No'],
              user_id:[res[0].user_id],
              created_on:[new Date(res[0].created_on)],
              expire_date:[new Date(res[0].expire_date)],
              DeletedUser:res[0].DeletedUser==true?'Yes':'No'
            })

          }else{
             this.deleteShow=false;
             this.deviceForm.reset();
             this.snackBar.open("No Data Found", '', {
                duration: 4000,
          });
          }
          
        })

  }

             deleteDevice(){
                      swal({                 
                             title: '<strong>Are you sure?</strong>',
                            icon: 'warning',
                            html: "You won't be able to revert this!",
                            showCloseButton: true,
                            focusConfirm: false,
                            // confirmButtonText: 'Reset today ODO',
                            confirmButtonText: 'Yes, delete it!',
                            // cancelButtonText: 'Reset total ODO',
                            // cancelButtonAriaLabel: 'Thumbs down'
                            cancelButtonText: 'No, cancel!',
                        }).then((result: { value: boolean; }) => {
                            if (result) {
                              var deletePayload = {
                              'userId' : this.data._id,
                              'deleteuser' : true
                            }
                            console.log(deletePayload);
                            this.contactService.deleteCostumer(deletePayload).subscribe(res=>{
                                swal({
                                 title: 'Deleted!',
                                 html:'Your file has been deleted.',
                                   icon:'success'
                                })
                                 this.deviceForm.reset();
                              },err=>{
                                console.log(err);
                                var message=JSON.parse(err._body)
                                swal({
                                 title:'Status: '+err.status ,
                                 html:message.message,
                                   icon:'warning'
                                })
                              })
                             
                            }
                          }
                        )
  }

    deleteDevicePermenatly(){
                      swal({                 
                             title: '<strong>Are you sure?</strong>',
                            icon: 'warning',
                            html: "User will be deleted permanantly",
                            showCloseButton: true,
                            focusConfirm: false,
                            // confirmButtonText: 'Reset today ODO',
                            confirmButtonText: 'Yes, delete it!',
                            // cancelButtonText: 'Reset total ODO',
                            // cancelButtonAriaLabel: 'Thumbs down'
                            cancelButtonText: 'No, cancel!',
                        }).then((result: { value: boolean; }) => {
                            if (result) {
                             
                              this.contactService.permanentDeluser(this.data._id).subscribe(res=>{
                                swal(
                                  'Deleted',
                                  'User Deleted',
                                  'success'
                                )
                                this.deviceForm.reset();
                              })
                            }
                          }
                        )
  }

 
  }
  
 
   
   

                       
  
                                 
                               
                               


