package de.hsadmin.mods.pac;

import static javax.persistence.CascadeType.ALL;
import static javax.persistence.FetchType.EAGER;
import static javax.persistence.FetchType.LAZY;
import static javax.persistence.GenerationType.SEQUENCE;

import java.io.Serializable;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

import de.hsadmin.core.model.AbstractEntity;
import de.hsadmin.mods.user.UnixUser;

@Entity(name = "Hives")
@Table(name = "hive")
@SequenceGenerator(name = "HivesSeqGen", sequenceName = "hive_hive_id_seq")
public class Hive extends AbstractEntity implements Serializable {
	
	private static final long serialVersionUID = -2270234313165009590L;

	@Id
	@GeneratedValue(strategy = SEQUENCE, generator = "HivesSeqGen")
	@Column(name = "hive_id")
	private long id;

	@Column(name = "hive_name", columnDefinition = "character varying(3)", unique = true)
	private String name;

	@JoinColumn(name = "inet_addr_id")
	@ManyToOne(fetch = EAGER)
	private INetAddress inetAddr;

	@Column(name = "description", columnDefinition = "character varying(100)")
	private String description;

	@OneToMany(fetch = LAZY, cascade = ALL, mappedBy = "hive")
	@OrderBy("name")
	private Set<Pac> pacs;

	public Hive() {
	}

	public Hive(String name, INetAddress inetAddr) {
		this.name = name;
		this.inetAddr = inetAddr;
	}

	public Hive(String name, INetAddress inetAddr, String desc) {
		this(name, inetAddr);
		this.description = desc;
	}

	public static String createQueryFromStringKey(String humanKey) {
		return "hiveName='" + humanKey + "'";
	}

	@Override
	public String createStringKey() {
		return getHiveName();
	}

	@Override
	public long id() {
		return id;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	@Override
	public String getHiveName() {
		return name;
	}

	public void setName(String hiveName) {
		this.name = hiveName;
	}

	public INetAddress getInetAddr() {
		return inetAddr;
	}

	public void setInetAddr(INetAddress inetAddr) {
		this.inetAddr = inetAddr;
	}

	public String getDescription() {
		return description;
	}

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

	public Set<Pac> getPacs() {
		return pacs;
	}

	public void setPacs(Set<Pac> pacs) {
		this.pacs = pacs;
	}

	@Override
	public boolean isNew() {
		return id == 0;
	}

	@Override
	public UnixUser owningUser(EntityManager em) {
		return null; // TODO: kinda somebody like root needed
	}
}
