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) {
        try {
            Jedis redis = JedisPoolInstance.pool.getResource();
            Integer userid = Integer.parseInt(redis.get(token));
            if (userid==null) {
                throw new WebApplicationException(Response.Status.UNAUTHORIZED);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    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;
    }
}


@@ -1100,24 +1100,55 @@
 ng token) %7B%0A
+        Integer userid = null;%0A
         try 
@@ -1221,32 +1221,24 @@
             
-Integer 
 userid = Int
@@ -1479,36 +1479,38 @@
 %0A        return 
-null
+userid
 ;%0A    %7D%0A%0A    pri

return userid from redis