import { DevicesService } from "./../devices.service";
import { Devices, DeviceDetails } from "../../../shared/models/app-model"
import { Component, OnInit, Renderer2 } from "@angular/core";
import { Table } from "primeng/table";
// import { DialogService } from "primeng/dynamicdialog";
// import { MessageService, ConfirmationService } from "primeng/api";
import { CookieService } from "ngx-cookie-service";
import { Router } from "@angular/router";
import { BaseService } from "src/app/shared/service/base.service";
import { UtilityService } from "src/app/shared/service/utility.service";

@Component({
  selector: "app-devices-list",
  templateUrl: "./devices-list.component.html",
  styleUrls: ["./devices-list.component.scss"],
  providers: [],
})
export class DevicesListComponent implements OnInit {
  devices: Devices[] = [];
  showLoader = false;
  deviceUrl = this.devicesService.getHost();
  statuses: any[] = [
    { name: "Online", value: true },
    { name: "Offline", value: false },
  ];
  selectedStatus = "";
  colsToShow: any = [
    {
      field: "test",
      header: "Test Header",
      display: "table-cell",
    },
    {
      field: "hiddenTest",
      header: "Hidden Column",
      display: "none",
    },
  ];

  isHeaderExpander = false;
  check: boolean = false;
  delete: boolean = false;
  sizes!: any[];
  selectedSize: any = "";
  myVariable: string = "";
  intervalId: any;

  constructor(
    // public dialogService: DialogService,
    // public messageService: MessageService,
    public renderer: Renderer2,
    public devicesService: DevicesService,
    // public confirmationService: ConfirmationService,
    private cookieService: CookieService,
    public baseService: BaseService,
    private router: Router,
    private helper:UtilityService
  )
   { }
  ngOnInit(): void {
    this.sizes = [
      { name: "Small", class: "p-datatable-sm" },
      { name: "Normal", class: "" },
      { name: "Large", class: "p-datatable-lg" },
    ];
    this.selectedSize = this.sizes[0];

    //this.getDevicesList();

    this.getDevices();

    //this.getDeviceOnlineStatus();
    this.isAuth();
  }

  ngOnDestroy() {
    this.stopDeviceOnlineStatusCheck();
  }

  clear(table: Table) {
    table.clear();
  }
  showSetExpiryDialog() {
    // const modalReference = this.dialogService.open(DevicesExpiryComponent, {
    //   header: "Set Devices Expiry",
    //   width: "1000px",
    //   height: "600px",
    // });
    // modalReference.onClose.subscribe((data: any) => {
    
        
    //     //this.getDevicesList();
    //     this.getDevices();
      
    // });
  }
  getDevices()
  {
    this.showLoader = true;
    //ANGULAR UPGRADE 16.2 subscribe is depricated
    this.devicesService.getDevicesList().subscribe(
      (response: any) => {
        const data = response.data;

        if (data && data.length) {
          this.devices = data;

        }
         this.showLoader = false;
      },
      (err) => {
        console.log(err);
        this.showLoader = false;
        this.devicesService.handleError(err);
      });

  }
  getDevicesList() {
    this.showLoader = true;
    //ANGULAR UPGRADE 16.2 subscribe is depricated
    this.devicesService.getDevicesList().subscribe(
      (data: any) => {
        if (data && data.length) {
          // console.log(data);
          this.devices = data;
          for (const device of this.devices) {
            var fdata = new URLSearchParams();
            fdata.append("domain", device.domain);
            //ANGULAR UPGRADE 16.2 subscribe is depricated
            this.devicesService.getCustomerOf_Devices(fdata).subscribe(
              (resp: any) => {
                //console.log(resp);

                device.Customername = resp[0].name;
              },
              (err: any) => {
                console.log(err);
              }
            );
            device.subdevices = this.devices.filter((x: any) => {
              return device.id === x.parent.toLowerCase();
            });
            var customProp: any = [];
            //addcustom Properties
            const normalProp = [
              "appPort”,”bytesRx",
              "bytesTx",
              "category",
              "connects",
              "created",
              "createdBy",
              "description",
              "domain",
              "hashedPassword",
              "host",
              "httpPort",
              "id",
              "lastConnect",
              "name",
              "online",
              "parent",
              "port",
              "protocol",
              "rdpPort",
              "serial",
              "server",
              "site",
              "sshPort",
              "tags",
              "targetHost",
              "targetPorts",
              "tenant",
              "type",
              "userAgent”,”version",
              "vncPort",
            ];
            for (const key of Object.keys(device)) {
              //console.log(`${key}: ${(device as {[key: string]: string})[key]}`);
              //if(!normalProp.includes(key))
              //  customProp[key]=device[`${key}`];
            }

            // console.log(device.subdevices)
          }
          //console.log(this.devices);
          this.devices = this.devices.filter((x) => {
            return x.parent === "";
          });
          this.devices.sort(function (x, y) {
            return x.online === y.online ? 0 : x ? -1 : 1;
          });
          this.devices.sort((a: any, b: any) => b.nearexpiry - a.nearexpiry);
        }
        this.showLoader = false;
      },
      (err) => {
        console.log(err);
        this.showLoader = false;
        this.devicesService.handleError(err);
      }
    );
  }
  

  showDialog() {
    // const modalReference = this.dialogService.open(CreateDeviceComponent, {
    //   header: "Create New Device",
    //   width: "400px",
    // });
    // modalReference.onClose.subscribe((data: any) => {
    //   if (data && data.action) {
    //     // this.messageService.add({ severity: 'success'});
    //     //this.getDevicesList();
    //     this.getDevices();
    //   }
    // });
  }

  makeDropdownActive(event: any) {
    setTimeout(() => {
      this.renderer.addClass(event.target, "active");
    }, 5);
  }

  showDeviceProperties(deviceDetails: any) {
    // const modalReference = this.dialogService.open(DevicePropertiesComponent, {
    //   header: "Device Properties",
    //   width: "1000px",
    //   height: "700px",
    //   data: deviceDetails,
    // });
    // modalReference.onClose.subscribe((data: any) => {
    //   if (data && data.action) {
    //     //this.getDevicesList();
    //     this.getDevicesList();
    //     // this.messageService.add({ severity: 'success', summary: 'Device Properties', detail: 'Device properties updated successfully' });
    //   }
    // });
  }

  deleteDevice(device: any) {
    // this.confirmationService.confirm({
    //   message: "Do you want to delete this device?",
    //   header: "Delete Confirmation",
    //   icon: "pi pi-info-circle",
    //   accept: () => {
    //     this.devicesService
    //       .deleteDevice(device.id)
    //       //ANGULAR UPGRADE 16.2 subscribe is depricated
    //       .subscribe(
    //         (respones: any) => {
    //           // this.messageService.add({
    //           //   severity: "info",
    //           //   summary: "Confirmed",
    //           //   detail: "Device delete request sent successfully",
    //           // });
    //           //this.getDevicesList();
    //           this.getDevicesList();
    //         },
    //         (err) => {
    //           console.log(err);
    //         }
    //       );
    //   },
    // });
  }

  copyToClipboard(id: string) {
    navigator.clipboard.writeText(id).then(
      () => {
        // this.messageService.add({
        //   severity: "success",
        //   summary: "Domain Copied Successfully",
        // });
      },
      (error) => {
        console.log(error);
      }
    );
  }

  copyToClipboardDeviceID(id: string) {
    navigator.clipboard.writeText(id).then(
      () => {
        // this.messageService.add({
        //   severity: "success",
        //   summary: "Device ID Copied Successfully",
        // });
      },
      (error) => {
        console.log(error);
      }
    );
  }

  openHelper(deviceId: string, app: string, port: string) {
    /*this.devicesService.getHelperParams(deviceId,app,port).subscribe((data: any) => {
      if (data && data.length) {
        //this.devices = data;
        console.log("data ---"+data);
        
      }
    }, err => {
      console.log(err);
    })*/

    //we have already obtain the token in in the login api use this for the wss
    let token = this.cookieService.get("token");
    var helperUrl =
      `macchina-rm+wss://${deviceId}.` +
      this.devicesService.getHost() +
      `?app=${app}&port=${port}&jwt=${token}`;
    window.open(helperUrl, "_blank");
  }

  openWebsite(device: any, deviceUrl: string) {
    var deviceId = device.id;
    //href="https://{{device.id}}.{{deviceUrl}}"
    let token = this.cookieService.get("token");
    var siteUrl = `https://${deviceId}.` + deviceUrl;

    const devideInfo = new URLSearchParams();

    devideInfo.append("action", "login");
    devideInfo.append("jwt", token);
    devideInfo.append("onsuccess", siteUrl);

    /*this.baseService.postData('', devideInfo)
        .subscribe((data: any) => {
          if (data && data.token) {
            window.open(siteUrl, "_blank");
          }
        }, (err: any) => {
          console.log(err);
          if (err.status === 401) {
            //this.loginError = true;
          }
        })
    */
    /*this.devicesService.createDeviceSession(deviceId,devideInfo).subscribe((data: any) => {
      if (data && data.length) {
        //this.devices = data;
        console.log("data ---"+data);
        window.open(siteUrl, "_blank");
        
      }
    }, err => {
      console.log(err);
    })*/

    //we have already obtain the token in in the login api use this for the wss

    var helperUrl =
      `${siteUrl}` + `?action=login&jwt=${token}&onsuccess=${siteUrl}`;
    if (device.httpPort == 8080)
      //rmgateway port is fixed to 8080
      helperUrl = `${siteUrl}`;
    //var helperUrl=`${siteUrl}`+`?action=login&jwt=${token}`;
    window.open(helperUrl, "_blank");
  }

  //  **************************************
  //  *                                    *
  //  *      Develop by Abhishek           *
  //  *                                    *
  //  **************************************
  //<------------- START------------->

  // isAuth(): boolean {

  //   if(this.hasPermission('authAdmin') && this.hasPermission('bundleAdmin') )
  //   {
  //     return true;
  //   }
  //   else
  //   {
  //     return false;
  //   }

  // }

  isAuth(): void {
    this.check =
      this.helper.hasPermission("Add Device") ;
    this.delete = this.helper.hasPermission("Delete Device");
    // console.log(this.delete  || this.check);
  }

  
  clearInput() {
    this.myVariable = "";
  }

    getDeviceOnlineStatus() {
      this.showLoader = true;

      /**
       * instead of creating a interval based online status messages
       * approhes are 
       *  1) have service wroket to constantly check the online status 
       *  2) implement the websocket to get the device status
       */
    }

    stopDeviceOnlineStatusCheck() {
      if (this.intervalId) {
        clearInterval(this.intervalId);
      }
    }
  //<------------- END------------->
}