package org.gcube.application.geoportal.model;

import java.time.LocalDateTime;

import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;

import org.gcube.application.geoportal.model.report.ConstraintCheck;
import org.gcube.application.geoportal.model.report.ValidationReport;
import org.gcube.application.geoportal.model.vre.GCubeUser;
import org.gcube.application.geoportal.model.vre.SocialManager;
import org.gcube.application.geoportal.utils.Serialization;

import com.fasterxml.jackson.core.JsonProcessingException;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@EqualsAndHashCode
public abstract class Record {

	
	//Generic Info
	@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
	private long id;	
	
	@Enumerated(EnumType.STRING)
	private RecordType recordType;
	private String version;
	private String licenzaID;
	
	@Enumerated(EnumType.STRING)
	private AccessPolicy policy;
	//Nome del progetto	
	private String nome;
	
	
	//Storage Info
	private String folderId;
	
	//Accounting
	private LocalDateTime lastUpdateTime;
	private String lastUpdateUser;
	private LocalDateTime creationTime;
	private String creationUser;
	
	public void registerUpdate() {
		GCubeUser user=SocialManager.getCurrentUser();
		this.setLastUpdateTime(LocalDateTime.now());
		this.setLastUpdateUser(user.getName());
	}
	
//	public String asJson() throws JsonProcessingException {
//		return Serialization.asJSON(this);
//	}
	
	public ValidationReport validate() {
		
		setDefaults();
		ValidationReport validator=new ValidationReport("Core metadata");
		validator.checkMandatory(getRecordType(), "Record Type");
		
		validator.checkMandatory(getNome(), "Nome");
	
		return validator; 
	}

	public void setDefaults() {
		GCubeUser user=SocialManager.getCurrentUser();
		LocalDateTime now=LocalDateTime.now();
		
		setVersion(ConstraintCheck.defaultFor(getVersion(),"1.0.0").evaluate());
		setPolicy(ConstraintCheck.defaultFor(getPolicy(), AccessPolicy.OPEN).evaluate());

		setLastUpdateTime(ConstraintCheck.defaultFor(getLastUpdateTime(),now).evaluate());
		setLastUpdateUser(ConstraintCheck.defaultFor(getLastUpdateUser(),user.getName()).evaluate());
		setCreationTime(ConstraintCheck.defaultFor(getCreationTime(),now).evaluate());
		setCreationUser(ConstraintCheck.defaultFor(getCreationUser(),user.getName()).evaluate());
		setLicenzaID(ConstraintCheck.defaultFor(getLicenzaID(),"CC-BY").evaluate());
	}
	

	
}
