{"ast":null,"code":"import { interval } from 'rxjs';\nimport { environment } from '../environments/environment';\nimport { devLog } from '../utils/dev-log'; // ajuste o caminho se necessário\nimport * as i0 from \"@angular/core\";\nimport * as i1 from \"../services/client.service\";\nimport * as i2 from \"../app.component\";\nimport * as i3 from \"@angular/common/http\";\nimport * as i4 from \"@angular/router\";\nimport * as i5 from \"../services/user.service\";\nimport * as i6 from \"@angular/common\";\nimport * as i7 from \"../clock/clock.component\";\nconst _c0 = () => [];\nfunction HomeComponent_tr_16_Template(rf, ctx) {\n  if (rf & 1) {\n    i0.ɵɵelementStart(0, \"tr\")(1, \"td\");\n    i0.ɵɵtext(2);\n    i0.ɵɵelementEnd();\n    i0.ɵɵelementStart(3, \"td\");\n    i0.ɵɵtext(4);\n    i0.ɵɵelementEnd();\n    i0.ɵɵelementStart(5, \"td\");\n    i0.ɵɵtext(6);\n    i0.ɵɵelementEnd();\n    i0.ɵɵelementStart(7, \"td\");\n    i0.ɵɵtext(8);\n    i0.ɵɵelementEnd()();\n  }\n  if (rf & 2) {\n    const ground_r1 = ctx.$implicit;\n    i0.ɵɵadvance(2);\n    i0.ɵɵtextInterpolate(ground_r1.name_ground);\n    i0.ɵɵadvance(2);\n    i0.ɵɵtextInterpolate(ground_r1.parking_ground_total);\n    i0.ɵɵadvance(2);\n    i0.ɵɵtextInterpolate(ground_r1.parking_ground_free);\n    i0.ɵɵadvance(2);\n    i0.ɵɵtextInterpolate(ground_r1.parking_ground_busy);\n  }\n}\nexport let HomeComponent = /*#__PURE__*/(() => {\n  class HomeComponent {\n    constructor(clientService, appComponent, http, router, userService) {\n      this.clientService = clientService;\n      this.appComponent = appComponent;\n      this.http = http;\n      this.router = router;\n      this.userService = userService;\n      this.userName = '';\n      this.userRole = '';\n      this.clients = [];\n      this.selectedClient = '';\n      this.clientLogo = 'assets/img/path-to-client-logo.png';\n      this.parkingData = [];\n      this.totalVagas = 0;\n      this.vagasLivres = 0;\n      this.vagasOcupadas = 0;\n    }\n    ngOnInit() {\n      this.startAutoUpdate(); // 🚀 dispara atualização automática\n      this.loadParkingData();\n      console.log('[ngOnInit] Componente Home inicializado.');\n      const userId = this.userService.getUserId();\n      console.log(`[ngOnInit] ID do usuário: ${userId}`);\n      this.appComponent.loadClients();\n      const storedClientId = localStorage.getItem('selectedClientId');\n      if (storedClientId) {\n        this.selectedClient = storedClientId;\n      }\n      const userAccessData = this.userService.getUserAccessData();\n      if (userAccessData?.parkingAccess?.length > 0) {\n        this.clients = userAccessData.parkingAccess.map(p => ({\n          id: p.id,\n          name: p.parkingName\n        }));\n        const selected = userAccessData.parkingAccess.find(p => p.id == +this.selectedClient) || userAccessData.parkingAccess[0];\n        this.selectedClient = selected.id.toString();\n        this.updateClientLogo(selected.id);\n        this.userName = `Nome do Usuário: ${selected.nome}`;\n        this.userRole = `Cargo do Usuário: ${selected.cargo}`;\n        this.clientService.setSelectedClient(selected.id);\n        this.getParkingData(selected.id);\n      }\n      this.clientSubscription = this.clientService.selectedClient$.subscribe(clientId => {\n        this.selectedClient = clientId;\n        localStorage.setItem('selectedClientId', clientId.toString());\n        this.updateClientLogo(+clientId);\n        this.getParkingData(+clientId);\n      });\n      this.startAutoUpdate();\n    }\n    onClientChange() {\n      const selectedClientObj = this.clients.find(client => client.id.toString() === this.selectedClient);\n      if (selectedClientObj) {\n        this.updateClientLogo(selectedClientObj.id);\n        localStorage.setItem('selectedClientId', selectedClientObj.id.toString());\n        const userAccessData = this.userService.getUserAccessData();\n        const selected = userAccessData?.parkingAccess?.find(p => p.id === selectedClientObj.id);\n        if (selected) {\n          this.userName = `Nome do Usuário: ${selected.nome}`;\n          this.userRole = `Cargo do Usuário: ${selected.cargo}`;\n        }\n        this.getParkingData(selectedClientObj.id);\n      }\n    }\n    updateClientLogo(clientId) {\n      this.clientLogo = `assets/img/cliente-${clientId}.png`;\n    }\n    getParkingData(id_customer) {\n      const url = `${environment.apiUrlBackEndExternaCache}/v1/spark-customers/ground/{\"id_customer\":${id_customer},\"id_park\":1}`;\n      const headers = {\n        device: 'manager'\n      };\n      devLog('[getParkingData] Iniciando requisição para:', url);\n      devLog('[getParkingData] Headers:', headers);\n      this.http.get(url, {\n        headers\n      }).subscribe(data => {\n        devLog('[getParkingData] Dados recebidos da API:', data);\n        if (Array.isArray(data)) {\n          this.parkingData = data;\n          devLog('[getParkingData] Dados atribuídos ao parkingData com sucesso.');\n        } else {\n          this.parkingData = [];\n          devLog('[getParkingData] Dados recebidos não são um array. parkingData setado como array vazio.');\n        }\n        this.calculateTotals();\n        devLog('[getParkingData] Totais calculados:', {\n          totalVagas: this.totalVagas,\n          vagasLivres: this.vagasLivres,\n          vagasOcupadas: this.vagasOcupadas\n        });\n      }, error => {\n        console.error('[getParkingData] Erro:', error);\n        devLog('[getParkingData] Erro na requisição:', error);\n        this.parkingData = []; // evita erro no template em caso de falha\n      });\n    }\n    calculateTotals() {\n      this.totalVagas = this.vagasLivres = this.vagasOcupadas = 0;\n      for (const ground of this.parkingData) {\n        this.totalVagas += ground.parking_ground_total;\n        this.vagasLivres += ground.parking_ground_free;\n        this.vagasOcupadas += ground.parking_ground_busy;\n      }\n    }\n    startAutoUpdate() {\n      devLog('[startAutoUpdate] Iniciando atualização automática a cada 10s.');\n      this.updateSubscription = interval(10000).subscribe(() => {\n        const userAccessData = this.userService.getUserAccessData();\n        const numericValue = +this.selectedClient;\n        devLog('[startAutoUpdate] Cliente selecionado:', numericValue);\n        devLog('[startAutoUpdate] Dados de acesso do usuário:', userAccessData);\n        const selected = userAccessData?.parkingAccess?.find(p => p.id === numericValue);\n        if (selected) {\n          this.userName = `Nome do Usuário: ${selected.nome}`;\n          this.userRole = `Cargo do Usuário: ${selected.cargo}`;\n          this.updateClientLogo(numericValue);\n          devLog('[startAutoUpdate] Nome e cargo atualizados:', {\n            nome: selected.nome,\n            cargo: selected.cargo\n          });\n        } else {\n          devLog('[startAutoUpdate] Nenhum acesso encontrado para o cliente:', numericValue);\n        }\n        devLog('[startAutoUpdate] acesso encontrado para o cliente:', numericValue);\n        this.getParkingData(numericValue);\n      });\n    }\n    stopAutoUpdate() {\n      if (this.updateSubscription) {\n        this.updateSubscription.unsubscribe();\n      }\n    }\n    loadParkingData() {\n      const clientId = localStorage.getItem('selectedClient') || '1';\n      const url = `${environment.apiUrlBackEndExternaCache}/v1/spark-customers/ground/{\"id_customer\":${clientId},\"id_park\":1}`;\n      const headers = {\n        device: 'manager'\n      };\n      this.http.get(url, {\n        headers\n      }).subscribe(data => {\n        // ✅ Garante que parkingData sempre seja um array\n        if (Array.isArray(data)) {\n          this.parkingData = data;\n        } else {\n          console.warn('[loadParkingData] Resposta inesperada:', data);\n          this.parkingData = [];\n        }\n        this.totalVagas = this.parkingData.reduce((sum, g) => sum + g.parking_ground_total, 0);\n        this.vagasLivres = this.parkingData.reduce((sum, g) => sum + g.parking_ground_free, 0);\n        this.vagasOcupadas = this.parkingData.reduce((sum, g) => sum + g.parking_ground_busy, 0);\n      }, error => {\n        console.error('[loadParkingData] Erro ao carregar dados de estacionamento:', error);\n        this.parkingData = []; // ❗ evita erro no template\n      });\n    }\n    ngOnDestroy() {\n      this.stopAutoUpdate();\n      this.clientSubscription?.unsubscribe();\n    }\n    logout() {\n      this.router.navigate(['/login']);\n    }\n    static #_ = this.ɵfac = function HomeComponent_Factory(t) {\n      return new (t || HomeComponent)(i0.ɵɵdirectiveInject(i1.ClientService), i0.ɵɵdirectiveInject(i2.AppComponent), i0.ɵɵdirectiveInject(i3.HttpClient), i0.ɵɵdirectiveInject(i4.Router), i0.ɵɵdirectiveInject(i5.UserService));\n    };\n    static #_2 = this.ɵcmp = /*@__PURE__*/i0.ɵɵdefineComponent({\n      type: HomeComponent,\n      selectors: [[\"app-home\"]],\n      decls: 35,\n      vars: 8,\n      consts: [[1, \"home-container\"], [1, \"parking-info\"], [1, \"parking-table\"], [4, \"ngFor\", \"ngForOf\"], [1, \"user-info\"], [1, \"user-details\"], [\"alt\", \"Client Logo\", 1, \"client-logo\", 3, \"src\"]],\n      template: function HomeComponent_Template(rf, ctx) {\n        if (rf & 1) {\n          i0.ɵɵelementStart(0, \"div\", 0)(1, \"div\", 1)(2, \"h1\");\n          i0.ɵɵtext(3, \"Informa\\u00E7\\u00F5es de Estacionamento\");\n          i0.ɵɵelementEnd();\n          i0.ɵɵelementStart(4, \"table\", 2)(5, \"thead\")(6, \"tr\")(7, \"th\");\n          i0.ɵɵtext(8, \"Andar\");\n          i0.ɵɵelementEnd();\n          i0.ɵɵelementStart(9, \"th\");\n          i0.ɵɵtext(10, \"Total de Vagas\");\n          i0.ɵɵelementEnd();\n          i0.ɵɵelementStart(11, \"th\");\n          i0.ɵɵtext(12, \"Vagas Livres\");\n          i0.ɵɵelementEnd();\n          i0.ɵɵelementStart(13, \"th\");\n          i0.ɵɵtext(14, \"Vagas Ocupadas\");\n          i0.ɵɵelementEnd()()();\n          i0.ɵɵelementStart(15, \"tbody\");\n          i0.ɵɵtemplate(16, HomeComponent_tr_16_Template, 9, 4, \"tr\", 3);\n          i0.ɵɵelementStart(17, \"tr\")(18, \"td\")(19, \"strong\");\n          i0.ɵɵtext(20, \"Total\");\n          i0.ɵɵelementEnd()();\n          i0.ɵɵelementStart(21, \"td\");\n          i0.ɵɵtext(22);\n          i0.ɵɵelementEnd();\n          i0.ɵɵelementStart(23, \"td\");\n          i0.ɵɵtext(24);\n          i0.ɵɵelementEnd();\n          i0.ɵɵelementStart(25, \"td\");\n          i0.ɵɵtext(26);\n          i0.ɵɵelementEnd()()()()();\n          i0.ɵɵelementStart(27, \"div\", 4);\n          i0.ɵɵelement(28, \"app-clock\");\n          i0.ɵɵelementStart(29, \"div\", 5)(30, \"div\");\n          i0.ɵɵtext(31);\n          i0.ɵɵelementEnd();\n          i0.ɵɵelementStart(32, \"div\");\n          i0.ɵɵtext(33);\n          i0.ɵɵelementEnd();\n          i0.ɵɵelement(34, \"img\", 6);\n          i0.ɵɵelementEnd()()();\n        }\n        if (rf & 2) {\n          i0.ɵɵadvance(16);\n          i0.ɵɵproperty(\"ngForOf\", ctx.parkingData || i0.ɵɵpureFunction0(7, _c0));\n          i0.ɵɵadvance(6);\n          i0.ɵɵtextInterpolate(ctx.totalVagas);\n          i0.ɵɵadvance(2);\n          i0.ɵɵtextInterpolate(ctx.vagasLivres);\n          i0.ɵɵadvance(2);\n          i0.ɵɵtextInterpolate(ctx.vagasOcupadas);\n          i0.ɵɵadvance(5);\n          i0.ɵɵtextInterpolate(ctx.userName);\n          i0.ɵɵadvance(2);\n          i0.ɵɵtextInterpolate(ctx.userRole);\n          i0.ɵɵadvance();\n          i0.ɵɵproperty(\"src\", ctx.clientLogo, i0.ɵɵsanitizeUrl);\n        }\n      },\n      dependencies: [i6.NgForOf, i7.ClockComponent],\n      styles: [\".home-container[_ngcontent-%COMP%]{display:flex;justify-content:space-between;padding:20px;background-color:#f7f7f7;color:#333;flex-wrap:wrap}.parking-info[_ngcontent-%COMP%]{flex:1;margin-right:20px}.parking-table[_ngcontent-%COMP%]{width:100%;border-collapse:collapse;background-color:#fff}.parking-table[_ngcontent-%COMP%]   th[_ngcontent-%COMP%], .parking-table[_ngcontent-%COMP%]   td[_ngcontent-%COMP%]{border:1px solid #ccc;padding:10px;text-align:center}.parking-table[_ngcontent-%COMP%]   th[_ngcontent-%COMP%]{background-color:#4caf50;color:#fff}.parking-table[_ngcontent-%COMP%]   td[_ngcontent-%COMP%]{background-color:#f2f2f2}.user-info[_ngcontent-%COMP%]{flex-basis:300px;text-align:right;background-color:#fff;padding:20px;border-radius:10px;box-shadow:0 0 10px #0000001a;margin-top:20px}.user-details[_ngcontent-%COMP%]{margin-top:20px}.client-logo[_ngcontent-%COMP%]{margin-top:20px;max-width:100%;height:auto}select[_ngcontent-%COMP%]{margin-top:10px;padding:5px;border-radius:5px;border:1px solid #ccc}app-clock[_ngcontent-%COMP%]{display:block;font-size:18px;color:#333;margin-bottom:20px}@media screen and (max-width: 768px){.home-container[_ngcontent-%COMP%]{flex-direction:column;padding:10px}.parking-info[_ngcontent-%COMP%]{margin-right:0;margin-bottom:20px}.user-info[_ngcontent-%COMP%]{text-align:left;padding:15px;box-shadow:none}.parking-table[_ngcontent-%COMP%]   th[_ngcontent-%COMP%], .parking-table[_ngcontent-%COMP%]   td[_ngcontent-%COMP%]{font-size:14px;padding:8px}}@media screen and (max-width: 480px){.home-container[_ngcontent-%COMP%]{padding:5px}.parking-info[_ngcontent-%COMP%]{margin-bottom:15px}.user-info[_ngcontent-%COMP%]{text-align:left;padding:10px}.parking-table[_ngcontent-%COMP%]   th[_ngcontent-%COMP%], .parking-table[_ngcontent-%COMP%]   td[_ngcontent-%COMP%]{font-size:12px;padding:6px}.user-info[_ngcontent-%COMP%], .parking-info[_ngcontent-%COMP%]{width:100%}select[_ngcontent-%COMP%]{font-size:14px}app-clock[_ngcontent-%COMP%]{font-size:16px}.client-logo[_ngcontent-%COMP%]{max-width:80%}}\"]\n    });\n  }\n  return HomeComponent;\n})();","map":null,"metadata":{},"sourceType":"module","externalDependencies":[]}