import {Component, OnInit} from '@angular/core';
import {HistoryService, PunishmentHistory} from '@api';
import { NgClass, NgOptimizedImage } from '@angular/common';
import {RemoveTrailingPeriodPipe} from '@pipes/RemoveTrailingPeriodPipe';
import {HistoryFormatService} from '../history-format.service';
import {ActivatedRoute, RouterLink} from '@angular/router';
import {catchError, map} from 'rxjs';
import {HeaderComponent} from '@header/header.component';

@Component({
  selector: 'app-details',
  imports: [
    NgOptimizedImage,
    RemoveTrailingPeriodPipe,
    HeaderComponent,
    RouterLink,
    NgClass
],
  templateUrl: './details.component.html',
  styleUrl: './details.component.scss'
})
export class DetailsComponent implements OnInit {
  type: 'all' | 'ban' | 'mute' | 'kick' | 'warn' = 'all';
  id: number = -1;
  punishment: PunishmentHistory | undefined;

  constructor(private route: ActivatedRoute,
              private historyApi: HistoryService,
              public historyFormat: HistoryFormatService) {
  }

  ngOnInit(): void {
    this.route.paramMap.subscribe(params => {
      switch (params.get('type')) {
        case 'ban':
          this.type = 'ban';
          break;
        case 'mute':
          this.type = 'mute';
          break;
        case 'kick':
          this.type = 'kick';
          break;
        case 'warn':
          this.type = 'warn';
          break;
        default:
          throw new Error("Invalid type");
      }
      this.id = Number(params.get('id') || '-1');
      this.loadPunishmentData();
    });
  }

  private loadPunishmentData() {
    if (!this.type || this.type === 'all' || this.id < 0 || isNaN(this.id)) {
      console.error("Invalid type or id");
      return;
    }
    this.historyApi.getHistoryById(this.type, this.id).pipe(
      map(punishment => {
        this.punishment = punishment;
      }),
      catchError(err => {
        console.error(err);
        return [];
      })
    ).subscribe();
  }
}
