import { CommonModule } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
import { DashboardWidgetModel } from 'src/app/shared/model/widget.model';
import { WidgetService } from 'src/app/shared/services/widget.service';

@Component({
  selector: 'app-widget1',
  templateUrl: './widget1.component.html',
  styleUrls: ['./widget1.component.css'],
  imports: [ CommonModule ],
  standalone: true
})
export class Widget1Component implements OnInit {

  dashboards: DashboardWidgetModel[] = [];
  dashboardUrl: SafeResourceUrl | null = null;
  private dashboardId: string | null = null;
  private portalAppBaseUrl = 'https://portal.myhr.co.th';

  constructor(
    private sanitizer: DomSanitizer,
    private widgetService: WidgetService
  ) { }

  ngOnInit() {
    this.loadDashboards();
  }

  loadDashboards(): void {
    this.widgetService.getDashboards().subscribe(dashboards => {
      this.dashboards = dashboards;
    });
  }

  onDashboardChange(event: Event): void {
    const selectElement = event.target as HTMLSelectElement;
    this.dashboardId = selectElement.value;
    if (this.dashboardId) {
      const url = `${this.portalAppBaseUrl}/#/embed/dashboard/${this.dashboardId}`;
      this.dashboardUrl = this.sanitizer.bypassSecurityTrustResourceUrl(url);
    } else {
      this.dashboardUrl = null;
    }
  }
}
