package com.gitrekt.resort.model.services;

import com.gitrekt.resort.hibernate.HibernateUtil;
import com.gitrekt.resort.model.entities.Guest;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

public class GuestService {

    private final EntityManager entityManager;
    
    public GuestService() {
        this.entityManager = HibernateUtil.getEntityManager();
    }
    
    @Override
    public void finalize() throws Throwable {
        super.finalize();
        this.entityManager.close();
    }
    
    public List<Guest> getCurrentlyCheckedInGuests() {
        return null;
    }

    public Guest getGuestById(Long id) {
        Guest guest = entityManager.getReference(Guest.class,id);
        return  guest;
    }

    public Guest getGuestByEmailAddress(String emailAddress) {
        try {
            String query 
                = "FROM Guest WHERE Guest.emailAddress = :emailAddress";
            Query q = entityManager.createQuery(query);
            q.setParameter("emailAddress", emailAddress);
            return (Guest) q.getSingleResult();
        } catch (EntityNotFoundException e) {
            return null;
        }
    }

    public void createNewGuest(Guest guest) {
        try {
            entityManager.getTransaction().begin();
            entityManager.persist(guest);
            entityManager.getTransaction().commit();
        } catch (PersistenceException e) {
            entityManager.getTransaction().rollback();
        }
    }

    public void updateGuest(Guest guest) {
        // TODO
    }
}

@@ -405,20 +405,16 @@
 anager;%0A
-    
 %0A    pub
@@ -499,28 +499,24 @@
 er();%0A    %7D%0A
-    
 %0A    @Overri
@@ -632,20 +632,16 @@
 ;%0A    %7D%0A
-    
 %0A    pub
@@ -684,24 +684,319 @@
 nGuests() %7B%0A
+        try %7B%0A            String query%0A                    = %22FROM Guest WHERE Guest.isCheckedIn = :param%22;%0A            Query q = entityManager.createQuery(query);%0A            q.setParameter(%22param%22, true);%0A            return q.getResultList();%0A        %7D catch (EntityNotFoundException e) %7B%0A    
         retu
@@ -1000,24 +1000,35 @@
 eturn null;%0A
+        %7D%0A%0A
     %7D%0A%0A    p
@@ -1124,16 +1124,17 @@
 t.class,
+ 
 id);%0A   
@@ -1145,17 +1145,16 @@
  return 
- 
 guest;%0A 
@@ -1264,10 +1264,13 @@
 uery
- 
 %0A
+    
     

Implement getCurrentCheckedInGuests