package org.bench4q.master.domain.service;

import java.util.List;

import org.apache.log4j.Logger;
import org.bench4q.master.domain.entity.Port;
import org.bench4q.master.helper.SessionHelper;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class PortPoolService {

	private SessionHelper sessionHelper = new SessionHelper();
	private Logger logger = Logger.getLogger(PortPoolService.class);

	public SessionHelper getSessionHelper() {
		return sessionHelper;
	}

	@Autowired
	public void setSessionHelper(SessionHelper sessionHelper) {
		this.sessionHelper = sessionHelper;
	}

	public boolean addPortToDBPool(int port) {
		Session session = this.getSessionHelper().openSession();
		Transaction transaction = session.beginTransaction();
		try {
			Port portDB = (Port) session.createCriteria(Port.class)
					.add(Restrictions.eq("port", port)).uniqueResult();
			if (portDB != null) {
				return false;
			}
			portDB = new Port();
			portDB.setPort(port);
			session.merge(portDB);
			transaction.commit();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			transaction.rollback();
			return false;
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	public boolean removePortFromDBPool(int id) {
		Session session = this.getSessionHelper().openSession();
		Transaction transaction = session.beginTransaction();
		try {
			Port portDB = (Port) session.createCriteria(Port.class)
					.add(Restrictions.eq("id", id)).uniqueResult();
			if (portDB == null) {
				this.logger
						.error("Port to delete don't exist where the portId is "
								+ id);
				return false;
			}
			session.delete(portDB);
			transaction.commit();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			transaction.rollback();
			return false;
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	@SuppressWarnings("unchecked")
	public Port getAPortNotInUse() {
		// If i do the HA in the pool, shall i lock this change for this port
		Session session = this.getSessionHelper().openSession();
		Transaction transaction = session.beginTransaction();
		Port port = null;
		try {
			List<Port> portList = (List<Port>) session
					.createCriteria(Port.class)
					.add(Restrictions.eq("inUse", false)).list();

			if (portList.isEmpty()) {
				return null;
			}

			port = portList.get(0);
			port.setInUse(true);
			transaction.commit();
			return port;
		} catch (Exception e) {
			e.printStackTrace();
			transaction.rollback();
			return null;
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	public boolean backPort(int port) {
		Session session = this.getSessionHelper().openSession();
		Transaction transaction = session.beginTransaction();
		try {
			System.out.println("back the port " + port + " to DB!");
			Port portEntity = (Port) session.createCriteria(Port.class)
					.add(Restrictions.eq("port", port)).uniqueResult();
			if (portEntity == null || !portEntity.isInUse()) {
				return false;
			}
			portEntity.setInUse(false);
			transaction.commit();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			transaction.rollback();
			return false;
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	@SuppressWarnings("unchecked")
	public List<Port> loadPortList() {
		Session session = this.getSessionHelper().openSession();
		try {
			List<Port> ports = session.createCriteria(Port.class).list();
			return ports;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	public boolean editPort(Port portInParam) {
		Session session = this.getSessionHelper().openSession();
		Transaction transaction = session.beginTransaction();
		try {
			Port portInDB = (Port) session.createCriteria(Port.class)
					.add(Restrictions.eq("port", portInParam.getPort()))
					.uniqueResult();
			portInDB.setInUse(portInParam.isInUse());
			transaction.commit();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			transaction.rollback();
			return false;
		} finally {
			if (session != null) {
				session.close();
			}
		}

	}
}
