package de.thpeetz.kontor.comics.data;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import de.thpeetz.kontor.common.data.*;
import io.hypersistence.utils.hibernate.type.basic.YearMonthDateType;
import jakarta.annotation.Nullable;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.Type;

import java.time.YearMonth;
import java.util.*;

@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
@Entity
public class Issue extends AbstractEntity {

    @ManyToOne
    @JoinColumn(name = "comic_id")
    @NotNull
    @JsonIgnoreProperties({ "issues" })
    private Comic comic;

    @ManyToOne
    @JoinColumn(name = "volume_id")
    @JsonIgnoreProperties({ "issues" })
    @Nullable
    private Volume volume;

    @ManyToOne
    @JoinColumn(name = "storyArc_id")
    @JsonIgnoreProperties({ "issues" })
    @Nullable
    private StoryArc storyArc;

    @NotEmpty
    private String issueNumber;

    @Nullable
    private String title;

    @Nullable
    @Type(YearMonthDateType.class)
    @Column(name = "published_on", columnDefinition = "date")
    private YearMonth publishedOn;

    private Boolean isRead;

    private Boolean inStock;

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "issue", cascade = CascadeType.REFRESH, orphanRemoval = true)
    @Nullable
    List<IssueWork> issueWorks;

    public String getComicTitle() {
        return comic.getTitle();
    }

    public String getVolumeName() {
        if (volume != null) {
            return volume.getName();
        }
        return null;
    }

    public String getFullTitle() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(this.getComic().getTitle());
        stringBuilder.append(" #");
        stringBuilder.append(this.getIssueNumber());
        if (this.title !=null && !this.title.isEmpty()) {
            stringBuilder.append(": ");
            stringBuilder.append(this.title);
        }
        return stringBuilder.toString();
    }

    @Override
    public String toString() {
        StringBuilder result = new StringBuilder();
        result.append("Issue{");
        result.append("comic=");
        result.append(comic);
        result.append(", volume=");
        result.append(volume);
        result.append(", storyArc=");
        result.append(storyArc);
        result.append(", issueNumber='");
        result.append(issueNumber);
        result.append(", title='");
        result.append(title);
        result.append(", publishedOn=");
        result.append(publishedOn);
        result.append(", isRead=");
        result.append(isRead);
        result.append(", inStock=");
        result.append(inStock);
        result.append("}");
        return result.toString();
    }
}
