import {
  Component,
  computed,
  inject
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { NgIcon, provideIcons } from '@ng-icons/core';
import {
  lucideBug,
  lucideCircleAlert,
  lucideClock3,
  lucideTrash2,
  lucideTriangleAlert
} from '@ng-icons/lucide';

import { DebuggingService } from '../../../../core/services/debugging.service';

@Component({
  selector: 'app-debugging-settings',
  standalone: true,
  imports: [CommonModule, NgIcon],
  viewProviders: [
    provideIcons({
      lucideBug,
      lucideCircleAlert,
      lucideClock3,
      lucideTrash2,
      lucideTriangleAlert
    })
  ],
  templateUrl: './debugging-settings.component.html'
})
export class DebuggingSettingsComponent {
  readonly debugging = inject(DebuggingService);

  readonly enabled = this.debugging.enabled;
  readonly isConsoleOpen = this.debugging.isConsoleOpen;
  readonly entryCount = computed(() => {
    return this.debugging.entries().reduce((sum, entry) => sum + entry.count, 0);
  });
  readonly errorCount = computed(() => {
    return this.debugging.entries().reduce((sum, entry) => {
      return sum + (entry.level === 'error' ? entry.count : 0);
    }, 0);
  });
  readonly warningCount = computed(() => {
    return this.debugging.entries().reduce((sum, entry) => {
      return sum + (entry.level === 'warn' ? entry.count : 0);
    }, 0);
  });
  readonly lastUpdatedLabel = computed(() => {
    const lastEntry = this.debugging.entries().at(-1);

    return lastEntry ? lastEntry.timeLabel : 'No logs yet';
  });

  onEnabledChange(event: Event): void {
    const input = event.target as HTMLInputElement;

    this.debugging.setEnabled(input.checked);
  }

  openConsole(): void {
    this.debugging.openConsole();
  }

  clearLogs(): void {
    this.debugging.clear();
  }
}
