import { Component, EventEmitter, OnInit, Output, TemplateRef, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { DeviceService } from '../device.service';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { RoleService } from '../../rolelist/role.service';
import { BaseService } from 'src/app/shared/service/base.service';
import { StorageService } from 'src/app/shared/service/storage.service';

@Component({
  selector: 'app-add-device',
  templateUrl: './add-device.component.html',
  styleUrl: './add-device.component.scss'
})
export class AddDeviceComponent implements OnInit {
  @ViewChild('addDeviceModal', { static: true }) addDeviceModal: TemplateRef<any>;

  @Output() DeviceAdded = new EventEmitter<void>();

  public deviceUUID: string = "";
  formSubmitted = false;
  check: boolean = false;
  tenants:any;
  

  deviceForm = new FormGroup({
    name: new FormControl('', Validators.required),
    id: new FormControl('', Validators.required),
    domain: new FormControl(''),
    Tenant: new FormControl(''),
  });
  

  constructor(
    private modalService: NgbModal,
    public deviceService: DeviceService,
    public roleService:RoleService,
    public baseService:BaseService,
    private storrage:StorageService
    ) {
      
    this.roleService.tenant$.subscribe(data => {
      this.tenants = data;
      console.log(this.tenants);
      
    });
  }

  hasRole(role:string){
    if(role==this.storrage.getItem('role'))
    {
      return true;
    }
    else{
      return false;
    }

  }


  ngOnInit(): void {
    this.deviceUUID = this.deviceService.generateUUID();
  }

  onSubmit() {

    const formData = new URLSearchParams();
      formData.append('deviceName', this.deviceForm.get('name').value);
      formData.append('deviceId', this.deviceForm.get('id').value);

      this.baseService.postData('devices/device', formData).subscribe(
        (data: any) => {
          if (data) {
          console.log(data);          

          if(this.deviceForm.get('Tenant').value != null){
            this.SaveDeviceTenant();
          }
          else{
            this.deviceForm.reset();
            this.modalService.dismissAll();
            this.DeviceAdded.emit();
          }   

        }
        },
        (err) => {
          console.log(err);
        }
        );
  }

  SaveDeviceTenant(){
    const formData = new URLSearchParams();
    const userid = this.storrage.getItem('user');

      formData.append('deviceUUID',  this.deviceForm.get('id').value);
      if('Tenant Admin'==this.storrage.getItem('role'))
        {
          this.baseService.getData(`tenants/getbyuserid/${userid}`).subscribe(
            (data: any) => {
              const tenantuuid = data.data[0].tenantUUID;
              formData.append('tenantId', tenantuuid);
              this.baseService.postData('devices/savedeviceMapping', formData).subscribe(
                (data: any) => {
                  if (data) {
                  console.log(data);          
                  this.deviceForm.reset();
                  this.modalService.dismissAll();
                  this.DeviceAdded.emit();
                  }
                },
                (err) => {
                  console.log(err);
                }
                );
            },
            error => {
              console.error('Request failed', error);
            }
          );        }
        else if('Admin'==this.storrage.getItem('role')){
          formData.append('tenantId', this.deviceForm.get('Tenant').value);
          this.baseService.postData('devices/savedeviceMapping', formData).subscribe(
            (data: any) => {
              if (data) {
              console.log(data);          
              this.deviceForm.reset();
              this.modalService.dismissAll();
              this.DeviceAdded.emit();
              }
            },
            (err) => {
              console.log(err);
            }
            );
        }

     
  }
  
  openModal() {
    this.modalService.open(this.addDeviceModal, { scrollable: true ,windowClass:'modal-holder', centered: true, backdrop: "static"});
  }

  closePopup() {
    this.formSubmitted = false;
    this.deviceForm.reset();
    // this.ref.close({});
  }
 



  

}
