package ru.ulstu.paper.model;

import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.NotBlank;
import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.UserContainer;
import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.file.model.FileData;
import ru.ulstu.user.model.User;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;

@Entity
public class Paper extends BaseEntity implements UserContainer {
    public enum PaperStatus {
        ATTENTION("Обратить внимание"),
        ON_PREPARATION("На подготовке"),
        ON_REVIEW("Отправлена на проверку"),
        ACCEPTED("Принята"),
        NOT_ACCEPTED("Не принята"),
        COMPLETED("Завершена (опубликована)"),
        DRAFT("Черновик"),
        FAILED("Провалены сроки");

        private String statusName;

        PaperStatus(String name) {
            this.statusName = name;
        }

        public String getStatusName() {
            return statusName;
        }
    }

    @NotBlank
    private String title;

    @Enumerated(value = EnumType.STRING)
    private PaperStatus status = PaperStatus.DRAFT;

    @Column(name = "create_date")
    @Temporal(TemporalType.TIMESTAMP)
    private Date createDate = new Date();

    @Column(name = "update_date")
    @Temporal(TemporalType.TIMESTAMP)
    private Date updateDate = new Date();

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = "paper_id", unique = true)
    @Fetch(FetchMode.SUBSELECT)
    @OrderBy("date")
    private List<Deadline> deadlines = new ArrayList<>();

    private String comment;

    private Boolean locked = false;

    @ManyToOne
    @JoinColumn(name = "file_id")
    private FileData fileData;

    @ManyToMany(fetch = FetchType.EAGER)
    private Set<User> authors = new HashSet<>();

    public PaperStatus getStatus() {
        return status;
    }

    public void setStatus(PaperStatus status) {
        this.status = status;
    }

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    public Date getUpdateDate() {
        return updateDate;
    }

    public void setUpdateDate(Date updateDate) {
        this.updateDate = updateDate;
    }

    public List<Deadline> getDeadlines() {
        return deadlines;
    }

    public void setDeadlines(List<Deadline> deadlines) {
        this.deadlines = deadlines;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public Boolean getLocked() {
        return locked;
    }

    public void setLocked(Boolean locked) {
        this.locked = locked;
    }

    public FileData getFileData() {
        return fileData;
    }

    public void setFileData(FileData fileData) {
        this.fileData = fileData;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Set<User> getAuthors() {
        return authors;
    }

    public void setAuthors(Set<User> authors) {
        this.authors = authors;
    }

    @Override
    public Set<User> getUsers() {
        return getAuthors();
    }

    public Optional<Deadline> getNextDeadline() {
        return deadlines
                .stream()
                .filter(deadline -> deadline.getDate() != null)
                .sorted(Comparator.comparing(Deadline::getDate))
                .filter(d -> d.getDate().after(new Date()))
                .findFirst();
    }

    public boolean lastDeadlineFailed() {
        return !deadlines
                .stream()
                .filter(deadline -> deadline.getDate() != null)
                .filter(d -> d.getDate().after(new Date()))
                .findAny()
                .isPresent();
    }
}
