package eu.eudat.data.entities;

import eu.eudat.data.converters.DateToUTCConverter;
import eu.eudat.data.entities.helpers.EntityBinder;
import eu.eudat.queryable.queryableentity.DataEntity;
import org.hibernate.annotations.GenericGenerator;

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

@Entity
@Table(name = "\"Lock\"")
public class Lock implements DataEntity<Lock, UUID> {

	@Id
	@GeneratedValue
	@GenericGenerator(name = "uuid2", strategy = "uuid2")
	@Column(name = "id", updatable = false, nullable = false, columnDefinition = "BINARY(16)")
	private UUID id;

	@Column(name = "\"Target\"", nullable = false)
	private UUID target;

	@ManyToOne(fetch = FetchType.EAGER)
	@JoinColumn(name = "\"LockedBy\"", nullable = false)
	private UserInfo lockedBy;

	@Column(name = "\"LockedAt\"")
	@Convert(converter = DateToUTCConverter.class)
	private Date lockedAt = new Date();

	@Column(name = "\"TouchedAt\"")
	@Convert(converter = DateToUTCConverter.class)
	private Date touchedAt = null;


	public UUID getId() {
		return id;
	}

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

	public UUID getTarget() {
		return target;
	}

	public void setTarget(UUID target) {
		this.target = target;
	}

	public UserInfo getLockedBy() {
		return lockedBy;
	}

	public void setLockedBy(UserInfo lockedBy) {
		this.lockedBy = lockedBy;
	}

	public Date getLockedAt() {
		return lockedAt;
	}

	public void setLockedAt(Date lockedAt) {
		this.lockedAt = lockedAt;
	}

	public Date getTouchedAt() {
		return touchedAt;
	}

	public void setTouchedAt(Date touchedAt) {
		this.touchedAt = touchedAt;
	}

	@Override
	public void update(Lock entity) {
		this.touchedAt = entity.touchedAt;
	}

	@Override
	public UUID getKeys() {
		return this.id;
	}

	@Override
	public Lock buildFromTuple(List<Tuple> tuple, List<String> fields, String base) {
		String currentBase = base.isEmpty() ? "" : base + ".";
		if (fields.contains(currentBase + "id")) this.id = EntityBinder.fromTuple(tuple, currentBase + "id");
		return this;
	}
}
