import { Component, OnInit, QueryList, TemplateRef, ViewChild, ViewChildren } from '@angular/core';

import { DecimalPipe } from '@angular/common';
import { Observable } from 'rxjs';

import { Device } from './device';
import { DeviceService } from './device.service';
import { NgbdSortableHeader, SortEvent } from './sortable.directive';
import { AddDeviceComponent } from './add-device/add-device.component';
import { DevicePropertiesComponent } from './device-properties/device-properties.component';
import { UtilityService } from 'src/app/shared/service/utility.service';
import { BaseService } from 'src/app/shared/service/base.service';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { StorageService } from 'src/app/shared/service/storage.service';
import { RoleService } from '../rolelist/role.service';
import { ToastService } from 'src/app/toast/toast-service';


@Component({
  selector: 'app-rolelist',
  templateUrl: './devicelist.component.html',
  styleUrls: ['./devicelist.component.scss'],
  providers: [DeviceService, DecimalPipe]
})

/**
 * Contacts user-list component
 */
export class DevicelistComponent implements OnInit {
  // bread crumb items
  @ViewChild(AddDeviceComponent, { static: true }) addUserComponent: AddDeviceComponent;
  @ViewChild(DevicePropertiesComponent, { static: true }) deviceProp: DevicePropertiesComponent;
  term: any;

  devices$: Observable<Device[]>;
  total$: Observable<number>;

  myproduct:any
  products:any
  devices: any[] = [];
  total: number = 0;
  tenants:any;
  deviceLimit:number=100;

  @ViewChildren(NgbdSortableHeader) headers: QueryList<NgbdSortableHeader>;

  constructor(public service: DeviceService,
    private utilityService: UtilityService,
    private baseService:BaseService,
    private sanitizer: DomSanitizer,
    private storrage:StorageService,
    private roleService:RoleService,
    public toastService: ToastService,
  ) {
    this.devices$ = service.device$;
    this.total$ = service.total$;

   
  }
  ngOnInit(): void {
    // this.service.fetchDevices();
    this.roleService.tenant$.subscribe(data => {
      this.tenants = data;      
    });

    this.addUserComponent.DeviceAdded.subscribe(() => {
      if('Tenant Admin'==this.storrage.getItem('role'))
        {
          this.getDevicesByTenant()
        }
        else if('Admin'==this.storrage.getItem('role')){
          this.getDevices();
        }
    });

    this.deviceProp.closeProperties.subscribe(() => {
      if('Tenant Admin'==this.storrage.getItem('role'))
        {
          this.getDevicesByTenant()
        }
        else if('Admin'==this.storrage.getItem('role')){
          this.getDevices();
        }
    });


    if('Tenant Admin'==this.storrage.getItem('role'))
    {
      this.getDevicesByTenant()

      
    }
    else if('Admin'==this.storrage.getItem('role')){
      this.getDevices();
    }
  }

  getDevicesByTenant(){
    const userid = this.storrage.getItem('user');

    this.baseService.getData(`tenants/getbyuserid/${userid}`).subscribe(
      (data: any) => {
        const tenantuuid = data.data[0].tenantUUID;
        this.baseService.getData(`devices/getAllDevicesbyTenant/${tenantuuid}`).subscribe(
          (data: any) => {
            if (data) {
              this.devices = data.data.map(device => {
                let ip = '';
                let location = '';
                device.deviceProp.forEach(prop => {
                  if (prop.propertyName === 'IP') {
                    ip = prop.propertyValue;
                  }
                  if (prop.propertyName === 'location') {
                    location = prop.propertyValue;
                  }
                });
                return { ...device, ip, location };
              });
              this.total = this.devices.length;
            }
          },
          (err) => {
            console.log(err);
          }
        );

        const formData = new URLSearchParams();
        formData.append('tenantId', tenantuuid);
        formData.append('attribute', 'device_quota');
  
        this.baseService.postData('subscriptions/validatePlan',formData).subscribe(
          (data: any) => {
            if (data) {
            console.log(data);       
            this.deviceLimit= Number(data.data)     
          }
          },
          (err) => {
            console.log(err);
          }
          );
      },
      error => {
        console.error('Request failed', error);
      }
    );
   
  }

    // Function to get a specific attribute by attrName
  getAttribute(attrName) {
    return this.myproduct.attributes.find(attr => attr.attrName === attrName);
  }


  getDevices(): void {
    this.baseService.getData('devices/getAllDevices').subscribe(
      (response: any) => {
        if (response && response.data) {
          this.devices = response.data.map(device => {
            let ip = '';
            let location = '';
            device.deviceProp.forEach(prop => {
              if (prop.propertyName === 'IP') {
                ip = prop.propertyValue;
              }
              if (prop.propertyName === 'location') {
                location = prop.propertyValue;
              }
            });
            return { ...device, ip, location };
          });
          this.total = this.devices.length;
        }
      },
      (err) => {
        console.log(err);
      }
    );
  }

  openDeviceSiteInNewTab(siteUrl: string): void {
    window.open(siteUrl, '_blank');
  }

  copyDeviceId(deviceId: string): void {
    if (navigator.clipboard) {
      navigator.clipboard.writeText(deviceId).then(() => {
        console.log('Device ID copied to clipboard!');
      }).catch(err => {
        console.error('Failed to copy: ', err);
      });
    } else {
      // Fallback for browsers that do not support Clipboard API
      const textArea = document.createElement('textarea');
      textArea.value = deviceId;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand('copy');
      document.body.removeChild(textArea);
      console.log('Device ID copied to clipboard!');
    }
  }

  openModal() {
    if(this.deviceLimit<=this.devices.length)
    {
      this.toastService.show('Your subscription limit has been exceeded. Please upgrade to a new subscription to add more devices.', { classname: 'bg-error text-light', delay: 3000 });
      return;
    }
    
    this.addUserComponent.openModal();
  }

  openDevicePropModal(device:any) {
    // console.log(device);
    
    this.baseService.getData(`devices/device/${device.deviceId}`).subscribe(
      (data: any) => {
        if (data) {
          // console.log(data);  
          this.deviceProp.device=data.data[0];
          this.deviceProp.openModal();
        }
      },
      (err) => {
        console.log(err);
      }
    );

  }

  hasPermission(permissions: string): boolean {
    return this.utilityService.hasPermission(permissions);
  }

}
