import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { JoyrideService } from 'ngx-joyride';
import { ToastrService } from "ngx-toastr";
import { ConfigService } from '@services/config.service';

@Component({
  selector: 'app-ogboot-status',
  templateUrl: './ogboot-status.component.html',
  styleUrls: ['./ogboot-status.component.css']
})
export class OgbootStatusComponent implements OnInit {
  baseUrl: string;
  diskUsage: any = {};
  servicesStatus: any = {};
  installedOglives: any[] = [];
  diskUsageChartData: any[] = [];
  loading: boolean = false;

  view: [number, number] = [1100, 500];

  gradient: boolean = true;
  showLegend: boolean = true;
  showLabels: boolean = true;
  isDoughnut: boolean = true;
  colorScheme: any = {
    domain: ['#FF6384', '#3f51b5']
  };

  constructor(
    private http: HttpClient,
    private joyrideService: JoyrideService,
    private configService: ConfigService,
    private toastService: ToastrService,
  ) {
    this.baseUrl = this.configService.apiUrl;
  }

  ngOnInit(): void {
    this.loadStatus();
  }

  loadStatus(): void {
    this.loading = true;
    this.http.get<any>(`${this.baseUrl}/og-boot/status`).subscribe(data => {
      this.diskUsage = data.message.disk_usage;
      this.servicesStatus = data.message.services_status;
      this.installedOglives = data.message.installed_oglives;

      this.diskUsageChartData = [
        {
          name: 'Usado',
          value: parseFloat(this.diskUsage.used)
        },
        {
          name: 'Disponible',
          value: parseFloat(this.diskUsage.available)
        }
      ];
      this.loading = false;

    }, error => {
      this.toastService.error('Error al sincronizar con el el servicio de og-boot');
      this.loading = false;
    });
  }

  getServices(): { name: string, status: string }[] {
    return Object.keys(this.servicesStatus).map(key => ({
      name: key,
      status: this.servicesStatus[key]
    }));
  }

  formatBytes(bytes: number): string {
    if (bytes >= 1e9) {
      return (bytes / 1e9).toFixed(2) + ' GB';
    } else if (bytes >= 1e6) {
      return (bytes / 1e6).toFixed(2) + ' MB';
    } else if (bytes >= 1e3) {
      return (bytes / 1e3).toFixed(2) + ' KB';
    } else {
      return bytes + ' B';
    }
  }

  iniciarTour(): void {
    this.joyrideService.startTour({
      steps: [
        'titleStep',
        'diskUsageStep',
        'servicesStatusStep',
        'oglivesStep'
      ],
      showPrevButton: true,
      themeColor: '#3f51b5'
    });
  }

}
