package org.sistema.hibernate.onetoonebidirxml.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.sistema.hibernate.onetoonebidirxml.HibernateSession;
import org.sistema.hibernate.onetoonebidirxml.models.Port;

/**
 * implementation of PortDAOInterface
 * @author Eugenia Pérez
 * @email eugenia_perez@cuatrovientos.org
 */
public class PortDAO implements PortDAOInterface {

	/* 
	 * selects one port by Id
	 * @param id
	 * @return Country
	 */
	public Port selectById(Long id) {
	    SessionFactory sessionFactory = HibernateSession.getSessionFactory();
	    Session session = sessionFactory.openSession();
	 
	    Port port = (Port) session.get(Port.class, id);
	    
	    session.close();
	    return port;
	}

	/*
	 * retrieves all ports from db
	 * @return List of ports
	 */
	public List<Port> selectAll() {
	    SessionFactory sessionFactory = HibernateSession.getSessionFactory();
	    Session session = sessionFactory.openSession();
	 
	    List<Port> ports = session.createQuery("from Port").list();
	    
	    session.close();
	    return ports;
	}
	

	/*
	 * inserts a new port in database
	 * port must come with the id set 
	 * @param new port
	 */
	public void insert(Port port) {
	    SessionFactory sessionFactory = HibernateSession.getSessionFactory();
	    Session session = sessionFactory.openSession();
	    session.beginTransaction();
	 
	    session.persist(port);    
	    
	    session.getTransaction().commit();	         
	    session.close();

	}

	/*
	 * updates port
	 * @param port to update
	 */
	public void update(Port port) {
	    SessionFactory sessionFactory = HibernateSession.getSessionFactory();
		    Session session = sessionFactory.openSession();	 
		    session.beginTransaction();
		 
		    session.merge(port); 
		    
		    session.getTransaction().commit();		 
		    session.close();
	}
	

	/*
	 * delete given port
	 * @param port to delete
	 */
	public void delete(Port port) {
	    SessionFactory sessionFactory = HibernateSession.getSessionFactory();
	    Session session = sessionFactory.openSession();	    
	    session.beginTransaction();
	    
	    session.delete(port);
	 
	    session.getTransaction().commit();
	    session.close();
	}

}
