/*-
 * ~~~~~~licensing~~~~~~
 * permission-impl
 * ==========
 * Copyright (C) 2020 - 2025 EmDev LLC
 * ==========
 * You may not use this file except in accordance with the License Terms of the Copyright
 * Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
 * rights to the Software and any copies are the property of the Copyright Holder. Unless
 * it is explicitly allowed the Copyright Holder, the User is prohibited from using the
 * Software for commercial purposes to provide services to third parties.
 * 
 * The Copyright Holder hereby declares that the Software is provided on an "AS IS".
 * Under no circumstances does the Copyright Holder guarantee or promise that the
 * Software provided by him will be suitable or not suitable for the specific purposes
 * of the User, that the Software will meet all commercial and personal subjective
 * expectations of the User, that the Software will work properly, without technical
 * errors, quickly and uninterruptedly.
 * 
 * Under no circumstances shall the Copyright Holder or its Affiliates is not liable
 * to the User for any direct or indirect losses of the User, his expenses or actual
 * damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
 * or damage to data, property, etc.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.esb.system.core.permission.jpa.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.hibernate.type.StringType;
import ru.entaxy.esb.system.core.permission.jpa.PermissionService;
import ru.entaxy.esb.system.core.permission.jpa.entity.Permission;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static ru.entaxy.esb.system.core.permission.common.PermissionConstants.ACTION_DEFAULT;

public class PermissionServiceImpl implements PermissionService {

    private static final Log LOG = LogFactory.getLog(PermissionServiceImpl.class);

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public Session getSession() {
        return sessionFactory.openSession();
    }

    @Override
    public List<Permission> list() {
        List<Permission> list;
        try (Session s = getSession()) {
            s.getTransaction().begin();
            CriteriaQuery<Permission> cq = s.getCriteriaBuilder().createQuery(Permission.class);
            cq.from(Permission.class);
            list = s.createQuery(cq).getResultList();
            s.getTransaction().commit();
            s.close();
        }

        return list;
    }

    @Override
    public Permission get(long id) {
        Permission permission;
        try (Session s = getSession()) {
            s.getTransaction().begin();

            Query<Permission> query = getQuery(s, id);
            permission = query.getSingleResult();

            s.getTransaction().commit();
            s.close();
        }
        return permission;
    }


    @Override
    public List<Permission> getAllById(long id, String type) {
        List<Permission> permissionList;
        try (Session s = getSession()) {
            s.getTransaction().begin();
            permissionList = getAllById(s, id, type);
            s.getTransaction().commit();
            s.close();
        }
        return permissionList;
    }

    @Override
    public List<Permission> getAllById(Session s, long id, String type) {
        CriteriaBuilder builder = s.getCriteriaBuilder();
        CriteriaQuery<Permission> criteriaQuery = builder.createQuery(Permission.class);
        Root<Permission> root = criteriaQuery.from(Permission.class);
        criteriaQuery.where(
                builder.or(
                        builder.and(
                                builder.equal(root.get("objectId"), id),
                                builder.equal(root.get("objectType"), type)),
                        builder.and(
                                builder.equal(root.get("subjectId"), String.valueOf(id)),
                                builder.equal(root.get("subjectType"), type))));

        return s.createQuery(criteriaQuery).getResultList();
    }

    @Override
    public Optional<Permission> fetch(long id) {
        Optional<Permission> permission;
        try (Session s = getSession()) {
            s.getTransaction().begin();

            Query<Permission> query = getQuery(s, id);
            permission = query.uniqueResultOptional();

            s.getTransaction().commit();
            s.close();
        }
        return permission;
    }

    private Query<Permission> getQuery(Session session, long id) {
        CriteriaBuilder builder = session.getCriteriaBuilder();
        CriteriaQuery<Permission> criteriaQuery = builder.createQuery(Permission.class);
        Root<Permission> root = criteriaQuery.from(Permission.class);
        criteriaQuery.where(builder.equal(root.get("id"), id));
        return session.createQuery(criteriaQuery);
    }

    @Override
    public List<Permission> get(long objectId, String objectType, String action) {
        List<Permission> permissionList;
        try (Session s = getSession()) {
            s.getTransaction().begin();
            permissionList = get(s, objectId, objectType, action);
            s.getTransaction().commit();
            s.close();
        }
        return permissionList;
    }

    @Override
    public List<Permission> get(Session s, long objectId, String objectType, String action) {
        CriteriaBuilder builder = s.getCriteriaBuilder();
        CriteriaQuery<Permission> criteriaQuery = builder.createQuery(Permission.class);
        Root<Permission> root = criteriaQuery.from(Permission.class);
        criteriaQuery.where(builder.equal(root.get("objectId"), objectId),
                builder.equal(root.get("objectType"), objectType),
                builder.equal(root.get("action"), action));
        return s.createQuery(criteriaQuery).getResultList();
    }


    @Override
    public Permission getByAllParameters(long objectId, String objectType, String subjectId,
                                         String subjectType, String action) {
        Permission permission;

        try (Session s = getSession()) {
            s.getTransaction().begin();
            permission = getByAllParameters(s, objectId, objectType, subjectId, subjectType, action);
            s.getTransaction().commit();
            s.close();
        }

        return permission;
    }

    @Override
    public Permission getByAllParameters(Session session, long objectId, String objectType, String subjectId,
                                         String subjectType, String action) {
        Query<Permission> query = getByAllParametersQuery(session, objectId, objectType, subjectId, subjectType, action);
        return query.getSingleResult();
    }

    @Override
    public Optional<Permission> fetchByAllParameters(long objectId, String objectType, String subjectId,
                                                     String subjectType, String action) {
        Optional<Permission> permission;

        try (Session s = getSession()) {
            s.getTransaction().begin();

            Query<Permission> query = getByAllParametersQuery(s, objectId, objectType, subjectId, subjectType, action);
            permission = query.uniqueResultOptional();

            s.getTransaction().commit();
            s.close();
        }

        return permission;
    }

    private Query<Permission> getByAllParametersQuery(Session s, long objectId, String objectType, String subjectId,
                                                      String subjectType, String action) {
        CriteriaBuilder builder = s.getCriteriaBuilder();
        CriteriaQuery<Permission> criteriaQuery = builder.createQuery(Permission.class);
        Root<Permission> root = criteriaQuery.from(Permission.class);
        criteriaQuery.select(root).where(
                builder.equal(root.get("objectId"), objectId),
                builder.equal(root.get("objectType"), objectType),
                builder.equal(root.get("subjectId"), subjectId),
                builder.equal(root.get("subjectType"), subjectType),
                builder.equal(root.get("action"), orElseGet(action))
        );
        return s.createQuery(criteriaQuery);
    }

    @Override
    public boolean existByAllParameters(long objectId, String objectType, String subjectId,
                                        String subjectType, String action) {
        if (objectId < 1) {
            return true;
        }
        boolean exists = false;
        try (Session s = getSession()) {
            s.getTransaction().begin();
            exists = (s
                    .createQuery("select 1 from Permission where exists ("
                            + "select 1 from Permission p where "
                            + "	p.objectId = ?0 "
                            + " AND p.objectType = ?1 "
                            + "	AND p.subjectId = ?2 "
                            + "	AND p.subjectType = ?3 "
                            + "	AND p.action = ?4"
                            + ")")
                    .setParameter(0, objectId)
                    .setParameter(1, objectType, StringType.INSTANCE)
                    .setParameter(2, subjectId, StringType.INSTANCE)
                    .setParameter(3, subjectType, StringType.INSTANCE)
                    .setParameter(4, orElseGet(action), StringType.INSTANCE)
                    .uniqueResult() != null);

            s.getTransaction().commit();
            s.close();
        }
        return exists;
    }

    @Override
    public Permission add(Permission permission) {
        return save(permission, false);
    }

    @Override
    public Permission add(long objectId, String objectType, String subjectId, String subjectType, String action) {
        Permission permission = new Permission();
        fillModel(permission, objectId, objectType, subjectId, subjectType, action);
        return add(permission);
    }

    @Override
    public Permission addIfNotExist(long objectId, String objectType, String subjectId, String subjectType, String action) {
        Optional<Permission> permission = fetchByAllParameters(objectId, objectType, subjectId, subjectType, action);
        return permission.orElseGet(() -> add(objectId, objectType, subjectId, subjectType, action));
    }

    private void fillModel(Permission permission, long objectId, String objectType, String subjectId,
                           String subjectType, String action) {
        permission.setObjectId(objectId);
        permission.setObjectType(objectType);
        permission.setSubjectId(subjectId);
        permission.setSubjectType(subjectType);
        permission.setAction(orElseGet(action));
    }

    @Override
    public List<Permission> addAll(long objectId, String objectType, List<List<String>> subjects) {
        List<Permission> permissions = new ArrayList<>();
        if (subjects != null && !subjects.isEmpty()) {
            for (List<String> subject : subjects) {
                try {
                    //TODO:make it in tttttransaction
                    permissions.add(
                            addIfNotExist(
                                    objectId,
                                    objectType,
                                    subject.get(0),
                                    subject.get(1),
                                    subject.get(2)));
                } catch (Exception e) {
                    LOG.error("Bulk addition of permission error " + e.getMessage());
                    LOG.trace(e);
                }
            }
        }
        return permissions;
    }

    @Override
    public List<Permission> addAll(List<Permission> permissionsToCreate) {
        List<Permission> permissions = new ArrayList<>();
        if (permissionsToCreate != null && !permissionsToCreate.isEmpty()) {
            for (Permission permission : permissionsToCreate) {
                try {
                    permissions.add(
                            addIfNotExist(
                                    permission.getObjectId(),
                                    permission.getObjectType(),
                                    permission.getSubjectId(),
                                    permission.getSubjectType(),
                                    permission.getAction()));
                } catch (Exception e) {
                    LOG.error("Bulk addition of permission error " + e.getMessage());
                    LOG.trace(e);
                }
            }
        }
        return permissions;
    }

    @Override
    public Permission update(Permission permission) {
        Optional<Permission> permissionOldOpt = fetch(permission.getId());

        return save(permission, permissionOldOpt.isPresent());
    }

    @Override
    public Permission update(long permissionId, long objectId, String objectType, String subjectId, String subjectType, String action) {
        Permission permission = get(permissionId);
        fillModel(permission, objectId, objectType, subjectId, subjectType, action);

        return save(permission, true);
    }

    public Permission save(Permission permission, boolean isExist) {
        try (Session s = getSession()) {
            s.getTransaction().begin();
            if (isExist) {
                s.update(permission);
            } else {
                s.persist(permission);
            }
            s.getTransaction().commit();
            s.close();
        }
        return permission;
    }

    @Override
    public void remove(long id) {
        try (Session s = getSession()) {
            s.getTransaction().begin();

            Permission permission = get(id);
            s.delete(Permission.class.getName(), permission);

            s.getTransaction().commit();
            s.close();
        }
    }

    @Override
    public void remove(long objectId, String objectType, String subjectId, String subjectType, String action) {
        try (Session s = getSession()) {
            s.getTransaction().begin();

            Permission permission = getByAllParameters(s, objectId, objectType, subjectId, subjectType, action);
            s.delete(Permission.class.getName(), permission);

            s.getTransaction().commit();
            s.close();
        }
    }

    @Override
    public void remove(long objectId, String objectType) {
        // TODO Auto-generated method stub

    }

    @Override
    public void remove(long objectId, String objectType, String action) {
        try (Session s = getSession()) {
            s.getTransaction().begin();

            List<Permission> permission = get(s, objectId, objectType, action);
            permission.forEach(s::delete);

            s.getTransaction().commit();
            s.close();
        }
    }

    @Override
    public void remove(String subjectId, String subjectType) {
        // TODO Auto-generated method stub

    }

    @Override
    public void remove(String subjectId, String subjectType, String action) {
        // TODO Auto-generated method stub

    }


    @Override
    public void removeAll(long objectId, String objectType) {
        try (Session s = getSession()) {
            s.getTransaction().begin();

            removeAll(s, objectId, objectType);

            s.getTransaction().commit();
            s.close();
        }
    }

    private String orElseGet(String action) {
        return action == null || action.isEmpty() ? ACTION_DEFAULT : action;
    }

    @Override
    public void removeAll(Session s, long objectId, String objectType) {
        List<Permission> permissionList = getAllById(s, objectId, objectType);
        for (Permission permission : permissionList) {
            s.delete(Permission.class.getName(), permission);
        }
    }

}
