import {Component, OnInit} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {ActivatedRoute, RouterLink} from "@angular/router";
import {ReplayData} from "../replays";
import {catchError, throwError} from "rxjs";
import {environment} from "../../environments/environment";
import {DecimalPipe, JsonPipe, NgForOf, NgIf, NgOptimizedImage} from "@angular/common";
import {calculateAccuracy} from "../format";
import {Title} from "@angular/platform-browser";
import {OsuGradeComponent} from "../../corelib/components/osu-grade/osu-grade.component";

interface ReplayPairStatistics {
  similarity: number;
  correlation: number;
}

interface ReplayPair {
  replays: ReplayData[];
  statistics: ReplayPairStatistics;
}

@Component({
  selector: 'app-view-replay-pair',
  standalone: true,
  imports: [
    NgIf,
    JsonPipe,
    DecimalPipe,
    NgOptimizedImage,
    NgForOf,
    RouterLink,
    OsuGradeComponent
  ],
  templateUrl: './view-replay-pair.component.html',
  styleUrl: './view-replay-pair.component.css'
})
export class ViewReplayPairComponent implements OnInit {

  isError = false;
  isLoading = true;

  private replay1Id: number | null = null;
  private replay2Id: number | null = null;

  pair: ReplayPair | null = null;

  constructor(
    private http: HttpClient,
    private activatedRoute: ActivatedRoute,
    private title: Title
  ) {}

  ngOnInit() {
    this.activatedRoute.params.subscribe(params => {
      this.replay1Id = params['replay1Id'];
      this.replay2Id = params['replay2Id'];
      if(this.replay1Id && this.replay2Id) {
        this.getReplayPairInfo();
      }
    });
  }

  getReplayPairInfo() {
    this.isLoading = true;
    this.http.get<ReplayPair>(`${environment.apiUrl}/pair/${this.replay1Id}/${this.replay2Id}`).pipe(
      catchError(error => {
        this.isLoading = false;
        this.isError = true;
        return throwError(() => new Error('An error occurred with the request: ' + error.message));
      })
    ).subscribe(replayPair => {
      this.isLoading = false;
      this.isError = false;
      this.pair = replayPair;
      this.title.setTitle(`${replayPair.replays[0].username} and ${replayPair.replays[1].username} on ${replayPair.replays[0].beatmap_title} (${replayPair.replays[0].beatmap_version}]`);
    });
  }

  protected readonly calculateAccuracy = calculateAccuracy;
}
