package info.bukova.isspst.data;

import info.bukova.isspst.Constants;
import info.bukova.isspst.Module;
import info.bukova.isspst.StringUtils;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import org.hibernate.search.annotations.IndexedEmbedded;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Entity
@Table(name = "SIGNED_DOCUMENTS")
public class SignedDocument extends BaseData {

	@Transient
    private String agendaName;

	@Column(name = "MODULE_NAME", length = Constants.LEN_TEXT)
	private String moduleName;

	@Column(name = "RECORD_ID")
	private int recordId;

	@Column(name = "NUMSER", length = Constants.LEN_TEXT)
	private String numser;

	@Column(name = "DESCRIPTION", length = Constants.LEN_DESCRIPTION)
	private String description;

	@Column(name = "SIGN_DATE")
	private Date signDate;

	@OneToMany(cascade = CascadeType.ALL, mappedBy = "signedDocument", orphanRemoval = true)
	@LazyCollection(LazyCollectionOption.TRUE)
	@IndexedEmbedded
	private List<SignedDocumentItem> items;

    public SignedDocument() {
    }

    public String getModuleName() {
		return moduleName;
	}

	public void setModuleName(String moduleName) {
		this.moduleName = moduleName;
	}

	public int getRecordId() {
		return recordId;
	}

	public void setRecordId(int recordId) {
		this.recordId = recordId;
	}

	public String getNumser() {
		return numser;
	}

	public void setNumser(String numser) {
		this.numser = numser;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public Date getSignDate() {
		return signDate;
	}

	public void setSignDate(Date signDate) {
		this.signDate = signDate;
	}

	public String getAgendaName() {
        if (!StringUtils.isNullOrEmpty(this.agendaName)) {
            return this.agendaName;
        }

		if (StringUtils.isNullOrEmpty(this.moduleName)) {
			return "";
		}

		for (Module m : Constants.MODULES) {
			if (this.moduleName.equals(m.getId())) {
				return m.getName();
			}
		}

		return "";
	}

    public void setAgendaName(String agendaName) {
        this.agendaName = agendaName;
    }

    public List<SignedDocumentItem> getItems() {
		return items;
	}

	public void setItems(List<SignedDocumentItem> items) {
		this.items = items;
	}

	public void addItem(SignedDocumentItem item) {
		if (items == null) {
			items = new ArrayList<SignedDocumentItem>();
		}

		item.setSignedDocument(this);
		this.items.add(item);
	}
}
