package com.csci4448.MediaManagementSystem.model.review;

import com.csci4448.MediaManagementSystem.model.user.User;
import com.csci4448.MediaManagementSystem.model.user.UserDAO;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import java.util.Iterator;
import java.util.List;

public class ReviewDAO {

    private SessionFactory sessionFactory;

    public ReviewDAO(){
        sessionFactory = new Configuration().configure().buildSessionFactory();

    }

    // Todo: add param for foreign key, attaching to media object
    public void addReview(String textReview, int rating, String username){

        User user = null;

        Session session = sessionFactory.openSession();
        Transaction transaction = null;

        user = (User) session.createQuery("from User where username = :username").setParameter("username", username).uniqueResult();


        try {

            transaction = session.beginTransaction();

            Review review = new Review();

            if (rating >= 1 && rating <= 5) {
                review.setRatingValue(rating);
            }

            if(textReview != null && !textReview.equals("")) {
                review.setReviewText(textReview);
            }

            review.setUser(user);


            transaction.commit();


        }

        catch (HibernateException ex) {
            if (transaction != null) {
                transaction.rollback();
            }
        }
        finally {
            session.close();
        }

    }


}



@@ -669,12 +669,11 @@
 lic 
-void
+int
  add
@@ -853,24 +853,120 @@
  null;%0A%0A
+%0A%0A        try %7B%0A%0A            transaction = session.beginTransaction();%0A%0A            try %7B%0A      
         
 user = (
@@ -957,16 +957,18 @@
         
+  
 user = (
@@ -1084,26 +1084,24 @@
 sult();%0A
-%0A%0A
         
 try %7B%0A%0A 
@@ -1084,38 +1084,37 @@
 sult();%0A        
-try %7B%0A
+    %7D
 %0A            tra
@@ -1114,49 +1114,81 @@
     
-transaction = session.beginTransaction();
+catch (HibernateException ex)%7B%0A                return -1;%0A            %7D%0A%0A
 %0A%0A  
@@ -1733,24 +1733,46 @@
 on.close();%0A
+            return 0;%0A
         %7D%0A%0A 

throw exception if user query doesn't return user