package com.example.todolist.entity;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Version;

import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.Where;
import org.hibernate.envers.Audited;
import org.hibernate.envers.RelationTargetAuditMode;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

@Entity
@Audited // ①追加
@Table(name = "todo")
@Where(clause = "is_deleted = 'N'")
@DynamicUpdate
@EntityListeners(AuditingEntityListener.class)
@Data
@EqualsAndHashCode(callSuper=true)
@ToString(exclude = "taskList")
public class Todo extends AuditInfo {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "id")
	private Integer id;

	@Column(name = "title")
	private String title;

	@Column(name = "importance")
	private Integer importance;

	@Column(name = "urgency")
	private Integer urgency;

	@Column(name = "deadline")
	private Date deadline;

	@Column(name = "done")
	private String done;

	@Column(name = "owner_id")
	private Integer ownerId;

	@Column(name = "completed_tasks")
	private Integer completedTasks;
	
	@Column(name = "version")
	@Version
	private Integer version;

	@Column(name = "is_deleted")
	private String isDeleted;
	
	@ManyToOne
	@JoinColumns ({
		@JoinColumn(name="category_code", referencedColumnName = "code"),
		@JoinColumn(name="category_locale", referencedColumnName = "locale"),
	})
	@Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED)// ②追加
	private Category category;


	@OneToMany(mappedBy = "todo", cascade = CascadeType.ALL)
	@OrderBy("id asc")
	private List<Task> taskList = new ArrayList<>();

	@ManyToOne
	@JoinColumn(name = "groups_id")
	@Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED)// ②追加
	private Groups groups;
	
	// Todoへの参照設定
	public void addTask(Task task) {
		task.setTodo(this);
		taskList.add(task);
	}
}
