import { Component, Input, TemplateRef, ViewChild, AfterViewInit, ChangeDetectorRef, Output, EventEmitter } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NgbModal, NgbNavOutlet } from '@ng-bootstrap/ng-bootstrap';
import * as L from 'leaflet';
import { BaseService } from 'src/app/shared/service/base.service';
import { v4 as uuidv4 } from 'uuid';

@Component({
  selector: 'app-device-properties',
  templateUrl: './device-properties.component.html',
  styleUrls: ['./device-properties.component.scss']
})
export class DevicePropertiesComponent {

  @ViewChild('deviceprop', { static: true }) deviceprop: TemplateRef<any>;
  @ViewChild('location', { static: true }) locationTemplate: TemplateRef<any>;

  map: L.Map;

  @Input() device: any;

  @Output() closeProperties = new EventEmitter<void>();

  deviceDetails: any = {};

  BasicProFrom: FormGroup;
  systemInfoFrom: FormGroup;
  networkInfoFrom: FormGroup;

  location: String
  isLocationTabActive = false; // Track if the Location tab is active

  constructor(
    private fb: FormBuilder,
    private modalService: NgbModal,
    private baseService: BaseService,
    private cdr: ChangeDetectorRef // Inject ChangeDetectorRef
  ) {
    this.BasicProFrom = this.fb.group({
      name: ['', Validators.required],
      id: ['', Validators.required],
      devicetype: [''],
      version: [''],
      server: [''],
      lastconnected: [''],
      host: [''],
      domain: [''],
      category: [''],
      serialNo: [''],
      connects: [''],
      createdOn: [''],
      CreatedBy: [''],
      description: ['']
    });

    this.systemInfoFrom = this.fb.group({
      byterx: [''],
      bytetx: [''],
      forwardedPort: [''],
      deviceIpAddress: [''],
      deviceWebServerPort: [''],
      statuss: [''],
      protocol: [''],
      deviceSshServerPort: [''],
      localDeviceAddress: [''],
      deviceSoftware: [''],
      operatingSystem:[''],
      architecture:[''],
      release:[''],
      numberOfCPU:[''],
      platform:[''],
      kernelVersion:[''],
      bootTime:[''],
      cpuHardware:[''],
      cpuRevision:[''],
      cpuSerialNumber:[''],
    });

    this.networkInfoFrom = this.fb.group({
      macAddress: [''],
      hostname: [''],
      interface: [''],
      interfaceFlag: [''],
      ipAddress: [''],
      ipv4: [''],
      ipv4FirstAddress: ['']
    });


  }

  ngOnInit(): void {
   }

  openModal() {
    this.modalService.open(this.deviceprop, {
      size: 'lg',
      scrollable: true,
      windowClass: 'modal-holder',
      centered: true,
      backdrop: "static"
    }).result.then((result) => {
      // Modal closed
    }, (reason) => {
      // Modal dismissed
    });

    // Initialize the map after a short delay to ensure the DOM is ready
    setTimeout(() => {
      this.mapDeviceToForm(this.device);
      this.cdr.detectChanges();
    }, 0);
  }

  // initializeMap(location: string) {
  //   if (!this.map) {
  //     this.map = L.map('map').setView([40.7128, -74.0060], 13); // Default to New York
  //     L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  //       maxZoom: 19,
  //     }).addTo(this.map);

  //     // Optionally, use a geocoding service to get coordinates based on location string
  //     // if (location) {
  //     //   this.geocodeLocation(location);
  //     // }
  //   }
  // }

  onTabClick(tabId: number) {
    if (tabId === 4) { // Assuming 4 is the ID for the Location tab
      this.isLocationTabActive=true;
      this.initializeMap();
    }
  }

 
  initializeMap() {
    if (this.isLocationTabActive) {
      const mapContainer = document.getElementById('map');
      if (mapContainer) {
        if (!this.map) {
          this.map = L.map('map').setView([40.7128, -74.0060], 13); // New York coordinates
          L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 19,
          }).addTo(this.map);

          L.marker([40.7128, -74.0060]).addTo(this.map)
            .bindPopup('New York')
            .openPopup();
        }
      } else {
        console.error('Map container not found');
      }
    }
  }


  geocodeLocation(location: string) {
    fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${location}`)
      .then(response => response.json())
      .then(data => {
        if (data && data.length > 0) {
          const lat = data[0].lat;
          const lon = data[0].lon;
          this.map.setView([lat, lon], 13);
          L.marker([lat, lon]).addTo(this.map)
            .bindPopup(location)
            .openPopup();
        }
      });
  }

  mapDeviceToForm(device: any) {
    if (device) {
      this.BasicProFrom.patchValue({
        id: device.deviceUUID || uuidv4(),
        name: device.deviceName || '',
        createdOn: device.createdOn || '',
        CreatedBy: device.createdBy || '',
        description: device.description || '',
        devicetype: device.deviceType || '',
        version: device.version || '',
        server: device.server || '',
        lastconnected: device.lastconnect || '',
        host: device.host || '',
        domain: device.domain || '',
        category: device.category || '',
        serialNo: device.serial || '',
        connects: device.connects || ''
      });

      this.systemInfoFrom.patchValue({
        byterx: device.byterx || '',
        bytetx: device.bytetx || '',
        forwardedPort: device.port || '',
        statuss: device.online ? 'Online' : 'Offline',
        protocol: device.protocol || '',
      });

      this.networkInfoFrom.patchValue({
        hostname: device.host || '',
      });

      if (device.deviceProperties && device.deviceProperties.length > 0) {
        device.deviceProperties.forEach((property: any) => {
          switch (property.propertyName) {
            case 'location':
              // this.initializeMap(property.propertyValue);
              break;
            case 'IP':
              this.systemInfoFrom.patchValue({ deviceIpAddress: property.propertyValue });
              this.systemInfoFrom.patchValue({ localDeviceAddress: property.propertyValue });
              this.networkInfoFrom.patchValue({ ipAddress: property.propertyValue });
              break;
            case "MAC Address":
                this.networkInfoFrom.patchValue({ macAddress: property.propertyValue });
                break;
            case "Interface":
                this.networkInfoFrom.patchValue({ interface: property.propertyValue });
                break;
            case "Interface Flag":
                this.networkInfoFrom.patchValue({ interfaceFlag: property.propertyValue });
                break;
            case "IPv4":
                this.networkInfoFrom.patchValue({ ipv4: property.propertyValue });
                break;
            case "IPv4 First Address":
                this.networkInfoFrom.patchValue({ ipv4FirstAddress: property.propertyValue });
                break;
            case "Device Web Server Port":
                this.systemInfoFrom.patchValue({ deviceWebServerPort: property.propertyValue });
                break
            case "Device Software":
                this.systemInfoFrom.patchValue({ deviceSoftware: property.propertyValue })
                break
            case "Operating system":
                  this.systemInfoFrom.patchValue({ operatingSystem: property.propertyValue })
                  break;
              case "Architecture":
                this.systemInfoFrom.patchValue({ Architecture: property.propertyValue })
                  break;
              case "Release":
                  this.systemInfoFrom.patchValue({ release: property.propertyValue })
                  break;
              case "Number of CPU":
                  this.systemInfoFrom.patchValue({ numberOfCPU: property.propertyValue })
                  break;
              case "Platform":
                  this.systemInfoFrom.patchValue({ platform: property.propertyValue })
                  break;
              case "Kernel version":
                  this.systemInfoFrom.patchValue({ kernelVersion: property.propertyValue })
                  break;
              case "Boot time":
                  this.systemInfoFrom.patchValue({ bootTime: property.propertyValue })
                  break;
              case "CPU Hardware":
                  this.systemInfoFrom.patchValue({ cpuHardware: property.propertyValue })
                  break;
              case "CPU Revision":
                  this.systemInfoFrom.patchValue({ cpuRevision: property.propertyValue })
                  break;
              case "CPU Serial Number":
                  this.systemInfoFrom.patchValue({ cpuSerialNumber: property.propertyValue })
                  break;
            default:
              console.log(`Unhandled property: ${property.propertyName}`);
          }
        });
      }
    }

    this.disableFields();
  }

  disableFields() {
    this.BasicProFrom.get('createdOn')?.disable();
    this.BasicProFrom.get('CreatedBy')?.disable();
    this.BasicProFrom.get('version')?.disable();
    this.BasicProFrom.get('server')?.disable();
    this.BasicProFrom.get('lastconnected')?.disable();
    this.BasicProFrom.get('connects')?.disable();
    this.BasicProFrom.get('id')?.disable();

    this.systemInfoFrom.get('byterx')?.disable();
    this.systemInfoFrom.get('bytetx')?.disable();
    this.systemInfoFrom.get('forwardedPort')?.disable();
    this.systemInfoFrom.get('statuss')?.disable();
    this.systemInfoFrom.get('protocol')?.disable();
    this.systemInfoFrom.get('localDeviceAddress')?.disable();
    this.systemInfoFrom.get('deviceSoftware')?.disable();
    this.systemInfoFrom.get('deviceIpAddress')?.disable();

    this.networkInfoFrom.get('macAddress')?.disable();
    this.networkInfoFrom.get('hostname')?.disable();
    this.networkInfoFrom.get('interface')?.disable();
    this.networkInfoFrom.get('interfaceFlag')?.disable();
    this.networkInfoFrom.get('ipAddress')?.disable();
    this.networkInfoFrom.get('ipv4')?.disable();
    this.networkInfoFrom.get('ipv4FirstAddress')?.disable();
  }

  onSubmit() {
    const formData = new URLSearchParams();
    formData.append('deviceName', this.BasicProFrom.get('name')?.value);
    formData.append('deviceId', this.BasicProFrom.get('id')?.value);
    formData.append('deviceDescription', this.BasicProFrom.get('description')?.value);
    formData.append('devicetype', this.BasicProFrom.get('devicetype')?.value);
    formData.append('host', this.BasicProFrom.get('host')?.value);
    formData.append('domain', this.BasicProFrom.get('domain')?.value);
    formData.append('category', this.BasicProFrom.get('category')?.value);
    formData.append('serial', this.BasicProFrom.get('serialNo')?.value);

    this.baseService.putData('devices/Updatedevice', formData).subscribe(
      (data: any) => {
        if (data) {
          console.log(data);
        }
      },
      (err) => {
        console.log(err);
      }
    );
  }

  dismissModal(){
    this.modalService.dismissAll();
    this.closeProperties.emit();
  }
}
