package industries.doublehelix.furrynotemanager;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.TreeSet;

public class Folder implements Comparable<Folder> {
	private int folderId = -1;
	private String name = "";
	private boolean isSystemFolder = false;
	
	public Folder() {
	}
	
	public Folder(String name, boolean isSystemFolder) {
		this.name = name;
		this.isSystemFolder = isSystemFolder;
	}
	
	public static Folder getFolder(int folderId) throws SQLException {
		TreeSet<Folder> folders = getFoldersByExtendedStatement("FOLDERID=" + folderId);
		return folders.first();
	}
	
	public static TreeSet<Folder> getAllFolders() throws SQLException {
		return getFoldersByExtendedStatement(null);
	}
	
	public static TreeSet<Folder> getFoldersByExtendedStatement(String where) throws SQLException {
		String wherePart = "";
		if (where != null && !where.isEmpty()) wherePart = " WHERE " + where;
		
		TreeSet<Folder> folders = new TreeSet<>();
		try (Statement s = DBTools.getInstance().getConnection().createStatement()) {
			try(ResultSet rs = s.executeQuery("SELECT * FROM FOLDERS" + wherePart)) {
				while(rs.next()) {
					Folder folder = new Folder(rs.getString("NAME"), rs.getBoolean("SYSTEMFOLDER"));
					folder.folderId = rs.getInt("FOLDERID");
					folders.add(folder);
				}
			}
		}
		return folders;
	}
	
	public static TreeSet<Folder> getFoldersFromUser(User user) throws SQLException {
		return getFoldersByExtendedStatement("FOLDERID IN (SELECT DISTINCT FOLDERID FROM NOTES WHERE USERID=" + user.getUserId() + ")");
	}
	
	public void removeFromDB() throws SQLException {
		if (this.isSystemFolder()) return; // not deleting them
		// sql constraints should throw an error when trying to remove a folder that has still notes in it
		try (Statement s = DBTools.getInstance().getConnection().createStatement()) {
			s.executeUpdate("DELETE FROM FOLDERS WHERE FOLDERID=" + this.folderId);
		}
	}
	
	public int getFolderId() {
		return folderId;
	}
	public void setFolderId(int folderId) {
		this.folderId = folderId;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public boolean isSystemFolder() {
		return isSystemFolder;
	}
	public void setSystemFolder(boolean isSystemFolder) {
		this.isSystemFolder = isSystemFolder;
	}

	@Override
	public int compareTo(Folder o) {
		if (o.name.equals(this.name)) {
			return Integer.compare(folderId, o.folderId);
		}
		return this.name.compareTo(o.name);
	}
	
	@Override
	public boolean equals(Object obj) {
		if (obj == null) return false;
		if (!(obj instanceof Folder)) return false;
		
		Folder folder = (Folder)obj;
		
		// not comparing noteid in case one side was not put into the DB
		return (folderId == folder.folderId && name.equals(folder.name) && isSystemFolder == folder.isSystemFolder);
	}
	
	@Override
	public String toString() {
		return this.name;
	}

}
