package industries.doublehelix.furrynotemanager;

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

public class Site implements Comparable<Site> {
	private int siteId = -1;
	private String name = "";
	
	private Site() {
	}
	
	public static Site getSite(int siteId) throws SQLException {
		try (Statement s = DBTools.getInstance().getConnection().createStatement()) {
			try(ResultSet rs = s.executeQuery("SELECT * FROM SITES WHERE SITEID=" + siteId)) {
				if (rs.next()) {
					Site site = new Site();
					site.siteId = siteId;
					site.name = rs.getString("NAME");
					return site;
				} else {
					return null; // not found
				}
			}
		}
	}
	
	public static TreeSet<Site> getAllSites() throws SQLException {
		TreeSet<Site> sites = new TreeSet<>();
		try (Statement s = DBTools.getInstance().getConnection().createStatement()) {
			try(ResultSet rs = s.executeQuery("SELECT * FROM SITES")) {
				while(rs.next()) {
					Site site = new Site();
					site.siteId = rs.getInt("SITEID");
					site.name = rs.getString("NAME");
					sites.add(site);
				}
			}
		}
		return sites;
	}
	
	public int getSiteId() {
		return siteId;
	}
	public void setSiteId(int siteId) {
		this.siteId = siteId;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	@Override
	public int compareTo(Site o) {
		if (o.name.equals(this.name)) {
			return Integer.compare(siteId, o.siteId);
		}
		return this.name.compareTo(o.name);
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == null) return false;
		if (!(obj instanceof Site)) return false;
		
		Site site = (Site)obj;
		return (siteId == site.siteId && name.equals(site.name));
	}
	
	@Override
	public String toString() {
		return this.getName();
	}
}
