package gov.va.vinci.dart.dms.biz;

import gov.va.vinci.dart.service.DartObjectFactory;

import java.io.File;

import javax.naming.NameNotFoundException;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

@Entity
@Table(name="repository",schema="hib")
public class Repository {

	private static Log log = LogFactory.getLog(Repository.class);
	
	// do not use this default path in production.  It can be set in app_prod.properties.
	public static String FILESTORE_PATH = null;
	
	public static int defaultRepository = 1;
	
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY) // because of course SQL Server doesn't support sequences.
	protected int id;

	// the name of the repo for user identification purposes
	@Column(name="name")
	private String name;

	@Column(name="location")
	private String location;
	
	@Column(name="encrypted", columnDefinition = "BIT", length = 1)
	private boolean encrypted = false;
	
	// the name of the secret key alias
	@Column(name="domain")
	private String domain;
	
	// the password to access the secret key in the keystore
	@Column(name="password")
	private String password;
	
	public String getRepositoryDirectoryName(final boolean useFilestorePath) {
		String repositoryPath = FILESTORE_PATH;
		
		// if not using the override from the JNDI environment var, use the db column
		if (repositoryPath == null || useFilestorePath == false) {
			repositoryPath = location;
		}
		
		// remove a tailing dir separator if present.
		int i = repositoryPath.lastIndexOf(File.separatorChar);
		if (i > 0) {
			return repositoryPath.substring(0,i);
		}
		
		return repositoryPath;
	}

	public static Repository findById(final int repositoryId) {
		return DartObjectFactory.getInstance().getRepositoryDAO().findById(repositoryId);
	}

	public boolean isEncrypted() {
		return encrypted;
	}

	public void setEncrypted(boolean encrypted) {
		this.encrypted = encrypted;
	}

	public int getId() {
		return id;
	}
	
	// TESTING ONLY
	public void setId(int id) {
		this.id = id;
	}
	
	public String getName() {
		return name;
	}

	// TESTING ONLY
	public void setName(String name) {
		this.name = name;
	}
	
	public String getDomain() {
		return domain;
	}

	public String getPassword() {
		return password;
	}

	public String getLocation() {
		return location;
	}

	// TESTING ONLY
	public void setLocation(String location) {
		this.location = location;
	}
	
}

