import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { FormsModule } from '@angular/forms';

import { MatchesService } from '@services/matches/matches.service';
import { MatchState } from '@interfaces/matches';

import { PlayerService } from '@services/player/player.service';

import { RefereeService } from '@services/referee/referee.service';
import { Referee, RefereeLevel } from '@interfaces/referee';

@Component({
  selector: 'app-matches-add',
  standalone: false,
  templateUrl: './matches-add.component.html',
  styleUrl: './matches-add.component.css',
})
export class MatchesAddComponent {
  formData = {
    player1Id: 0,
    player1FirstName: '',
    player1Name: '',
    player1Club: '',

    player2Id: 0,
    player2FirstName: '',
    player2Name: '',
    player2Club: '',

    refereeId: 0,
    refereeFirstName: '',
    refereeName: '',
    refereelevel: 0,

    city: '',
    country: '',
    weapon: '',
    date: '',
  };

  constructor(
    private matchService: MatchesService,
    private playerService: PlayerService,
    private refereeService: RefereeService,
    private router: Router
  ) {}

  onSubmit(): void {
    this.playerService
      .getOrCreateByName(
        this.formData.player1FirstName,
        this.formData.player1Name,
        this.formData.player1Club
      )
      .subscribe((player1) => {
        this.formData['player1Id'] = player1.id;

        this.playerService
          .getOrCreateByName(
            this.formData.player2FirstName,
            this.formData.player2Name,
            this.formData.player2Club
          )
          .subscribe((player2) => {
            this.formData['player2Id'] = player2.id;

            this.refereeService
              .getOrCreateByName(
                this.formData.refereeFirstName,
                this.formData.refereeName,
                this.formData.refereelevel
              )
              .subscribe((referee) => {
                this.formData['refereeId'] = referee.id;

                const matchPayload = {
                  refereeID: referee.id,
                  player1ID: player1.id,
                  score1: 0,
                  player2ID: player2.id,
                  score2: 0,
                  country: this.formData.country,
                  city: this.formData.city,
                  weapon: this.formData.weapon,
                  date: new Date(this.formData.date),
                  state: MatchState.NOT_STARTED,
                };

                this.matchService.create(matchPayload).subscribe(() => {
                  this.router.navigate(['/matches']);
                });
              });
          });
      });
  }
}
