package tracker_java.Utilities;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import redis.clients.jedis.Jedis;
import tracker_java.Models.HibernateUtil;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import java.util.regex.Pattern;

import static tracker_java.Models.HibernateUtil.getOneItemFromQuery;

/**
 * Created by cristian on 11/11/15.
 */

public final class PermissionsChecker {

    private boolean userIsAdmin(Integer memberId) {
        Session s = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = s.beginTransaction();
        Query isAdminQuery = s.createQuery("select admin from MemberEntity where memberid = :memberid").setParameter("memberid", memberId);
        boolean isAdmin = false;
        try {
            isAdmin = (boolean) isAdminQuery.list().get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        s.flush();
        tx.commit();
        s.close();
        return isAdmin;
    }

    private static Integer getUserIdFromToken(String token) {
        Integer userid = null;
        try {
            Jedis redis = JedisPoolInstance.pool.getResource();
            userid = Integer.parseInt(redis.get(token));
            if (userid==null) {
                throw new WebApplicationException(Response.Status.UNAUTHORIZED);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userid;
    }

    private static String getTokenFromHeader(String bareHeader) {
        try {
            String[] typeAndToken = bareHeader.split(Pattern.quote(" "));
            if (typeAndToken[0].equals("Bearer") && typeAndToken[1].length() > 0) {
                return typeAndToken[1];
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            throw new WebApplicationException(Response.Status.UNAUTHORIZED);
        }
        return null;
    }

    public static int getUserIdFromAuthorization(String authorization){
        return getUserIdFromToken(getTokenFromHeader(authorization));
    }

    /*
    get userid from token
    get projectid from itemid
    get memberproject junction entry
    >= 2
     */
    public static boolean checkPermissionComment(Integer itemid, String authorization) {
        Integer userid = getUserIdFromToken(getTokenFromHeader(authorization));
        Integer projectId = (Integer) getOneItemFromQuery(String.format("SELECT projectid FROM ItemEntity WHERE id = '%s'",itemid));
        Integer permission = (Integer) getOneItemFromQuery(String.format("SELECT position FROM MemberprojectEntity WHERE memberid = '%s' AND projectid = '%s'", userid, projectId));
        return permission >= 2;
    }

    /*
    get userid from token
    get projectid from taskid
    get memberproject entry
    == 3
     */
    public static boolean checkPermissionWrite(int taskId, String authorization) {
        Integer userid = getUserIdFromToken(getTokenFromHeader(authorization));
        Integer projectId = (Integer) getOneItemFromQuery(String.format("SELECT projectid FROM ItemEntity WHERE id = '%s'",taskId));
        Integer permission = (Integer) getOneItemFromQuery(String.format("SELECT position FROM MemberprojectEntity WHERE memberid = '%s' AND projectid = '%s'", userid, projectId));
        return permission == 3;
    }

    /*
    get userid from token
    get projectid from taskid
    get memberproject entry
    >= 1
     */
    public static boolean checkPermissionRead(int taskId, String authorization) {
        Integer userid = getUserIdFromToken(getTokenFromHeader(authorization));
        Integer projectId = (Integer) getOneItemFromQuery(String.format("SELECT projectid FROM ItemEntity WHERE id = '%s'",taskId));
        Integer permission = (Integer) getOneItemFromQuery(String.format("SELECT position FROM MemberprojectEntity WHERE memberid = '%s' AND projectid = '%s'", userid, projectId));
        return permission >= 1;
    }

    public static boolean checkWritePermissionToProject(Integer projectid, String authorization) {
        Integer userid = getUserIdFromToken(getTokenFromHeader(authorization));
        Integer permission = (Integer) getOneItemFromQuery(String.format("SELECT position FROM MemberprojectEntity WHERE memberid = '%s' AND projectid = '%s'", userid, projectid));
        return permission >= 3;
    }
}


@@ -1274,28 +1274,92 @@
 ));%0A        
-    
+%7D catch (Exception e) %7B%0A            e.printStackTrace();%0A        %7D%0A%09
 if (userid==
@@ -1362,36 +1362,25 @@
 id==null) %7B%0A
-            
+%09
     throw ne
@@ -1440,95 +1440,9 @@
 D);%0A
-            %7D%0A        %7D catch (Exception e) %7B%0A            e.printStackTrace();%0A        
+%09
 %7D%0A  
@@ -1531,24 +1531,46 @@
 reHeader) %7B%0A
+%09String token = null;%0A
         try 
@@ -1745,22 +1745,23 @@
         
-return
+token =
  typeAnd
@@ -1936,32 +1936,125 @@
 ZED);%0A        %7D%0A
+%09if (token==null) %7B%0A%09    throw new WebApplicationException(Response.Status.UNAUTHORIZED);%0A%09%7D%0A
         return n
@@ -2052,20 +2052,21 @@
  return 
-null
+token
 ;%0A    %7D%0A
@@ -2218,32 +2218,34 @@
   %7D%0A%0A    /*%0A    
+  
 get userid from 
@@ -2242,32 +2242,34 @@
 erid from token%0A
+  
     get projecti
@@ -2282,24 +2282,26 @@
  itemid%0A    
+ 
+ 
 get memberpr
@@ -2329,14 +2329,15 @@
     
+  
 %3E= 2%0A
- 
     
@@ -2864,32 +2864,34 @@
   %7D%0A%0A    /*%0A    
+  
 get userid from 
@@ -2888,32 +2888,34 @@
 erid from token%0A
+  
     get projecti
@@ -2924,32 +2924,34 @@
 from taskid%0A    
+ 
+ 
 get memberprojec
@@ -2966,14 +2966,15 @@
     
+  
 == 3%0A
- 
     
@@ -3499,24 +3499,26 @@
 %0A    /*%0A    
+  
 get userid f
@@ -3523,24 +3523,26 @@
  from token%0A
+  
     get proj
@@ -3559,24 +3559,26 @@
  taskid%0A    
+ 
+ 
 get memberpr
@@ -3597,14 +3597,15 @@
     
+  
 %3E= 1%0A
- 
     

check for null on userid from redis and auth header contents;