package fr.titionfire.ffsaf.data.model;

import fr.titionfire.ffsaf.utils.CompetitionSystem;
import fr.titionfire.ffsaf.utils.ScoreEmbeddable;
import io.quarkus.runtime.annotations.RegisterForReflection;
import jakarta.persistence.*;
import lombok.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@RegisterForReflection

@Entity
@ToString
@Table(name = "match")
public class MatchModel {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;

    @Column(name = "system_type")
    CompetitionSystem system;
    Long systemId;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "c1", referencedColumnName = "id")
    MembreModel c1_id = null;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "c1_guest", referencedColumnName = "id")
    CompetitionGuestModel c1_guest = null;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "c2", referencedColumnName = "id")
    MembreModel c2_id = null;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "c2_guest", referencedColumnName = "id")
    CompetitionGuestModel c2_guest = null;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "id_category", referencedColumnName = "id")
    CategoryModel category = null;

    long category_ord = 0;

    boolean isEnd = true;

    Date date = null;

    @ElementCollection(fetch = FetchType.EAGER)
    @CollectionTable(name = "score", joinColumns = @JoinColumn(name = "id_match"))
    List<ScoreEmbeddable> scores = new ArrayList<>();

    char poule = 'A';

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = "match", referencedColumnName = "id")
    List<CardboardModel> cardboard = new ArrayList<>();

    public String getC1Name() {
        if (c1_id != null)
            return c1_id.fname + " " + c1_id.lname;
        if (c1_guest != null)
            return c1_guest.fname + " " + c1_guest.lname;
        return "";
    }

    public String getC2Name() {
        if (c2_id != null)
            return c2_id.fname + " " + c2_id.lname;
        if (c2_guest != null)
            return c2_guest.fname + " " + c2_guest.lname;
        return "";
    }

    public int win() {
        int sum = 0;
        for (ScoreEmbeddable score : this.getScores()) {
            if (score.getS1() == -1000 || score.getS2() == -1000)
                continue;

            if (score.getS1() > score.getS2())
                sum++;
            else if (score.getS1() < score.getS2())
                sum--;
        }
        return sum;
    }
}
