/*-
 * ~~~~~~licensing~~~~~~
 * events-impl
 * ==========
 * Copyright (C) 2020 - 2023 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.events.jpa.impl;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import ru.entaxy.esb.system.core.events.common.SubscriptionType;
import ru.entaxy.esb.system.core.events.jpa.SystemSubscriptionService;
import ru.entaxy.esb.system.core.events.jpa.entity.EventTopic;
import ru.entaxy.esb.system.core.events.jpa.entity.SystemSubscription;
import ru.entaxy.esb.system.core.permission.common.PermissionConstants;
import ru.entaxy.esb.system.core.permission.jpa.PermissionService;
import ru.entaxy.esb.system.jpa.entity.System;

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

public class SystemSubscriptionServiceImpl implements SystemSubscriptionService {

    private SessionFactory sessionFactory;
    private PermissionService permissionService;


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

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

    public PermissionService getPermissionService() {
        return permissionService;
    }

    public void setPermissionService(PermissionService permissionService) {
        this.permissionService = permissionService;
    }

    @Override
    public List<SystemSubscription> list() {
        List<SystemSubscription> list;

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

            CriteriaQuery<SystemSubscription> cq = s.getCriteriaBuilder().createQuery(SystemSubscription.class);
            cq.from(SystemSubscription.class);
            list = s.createQuery(cq).getResultList();

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

        return list;
    }

    @Override
    public List<SystemSubscription> listByDeleted(boolean deleted) {
        List<SystemSubscription> list;

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

            CriteriaBuilder builder = s.getCriteriaBuilder();
            CriteriaQuery<SystemSubscription> criteriaQuery = builder.createQuery(SystemSubscription.class);
            Root<SystemSubscription> root = criteriaQuery.from(SystemSubscription.class);
            criteriaQuery.where(builder.equal(root.get("deleted"), deleted));
            list = s.createQuery(criteriaQuery).getResultList();

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

        return list;
    }

    @Override
    public SystemSubscription get(long id) {
        SystemSubscription systemSubscriptionRegistry;

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

            CriteriaBuilder builder = s.getCriteriaBuilder();
            CriteriaQuery<SystemSubscription> criteriaQuery = builder.createQuery(SystemSubscription.class);
            Root<SystemSubscription> root = criteriaQuery.from(SystemSubscription.class);
            criteriaQuery.where(builder.equal(root.get("id"), id));
            systemSubscriptionRegistry = s.createQuery(criteriaQuery).getSingleResult();

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

        return systemSubscriptionRegistry;
    }

    @Override
    public List<SystemSubscription> getBySystem(long systemId) {
        List<SystemSubscription> list;

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

            CriteriaBuilder builder = s.getCriteriaBuilder();
            CriteriaQuery<SystemSubscription> criteriaQuery = builder.createQuery(SystemSubscription.class);
            Root<SystemSubscription> root = criteriaQuery.from(SystemSubscription.class);
            Join<SystemSubscription, System> systemJoin = root.join("system");
            criteriaQuery.where(builder.equal(systemJoin.get("id"), systemId));
            list = s.createQuery(criteriaQuery).getResultList();

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

        return list;
    }

    @Override
    public SystemSubscription getBySystemAndTopic(long systemId, long eventTopicId) {
        SystemSubscription systemSubscriptionRegistry;

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

            CriteriaBuilder builder = s.getCriteriaBuilder();
            CriteriaQuery<SystemSubscription> criteriaQuery = builder.createQuery(SystemSubscription.class);
            Root<SystemSubscription> root = criteriaQuery.from(SystemSubscription.class);
            Join<SystemSubscription, System> systemJoin = root.join("system");
            Join<SystemSubscription, EventTopic> eventTopicJoin = root.join("eventTopic");
            criteriaQuery.where(builder.and(
                    builder.equal(systemJoin.get("id"), systemId),
                    builder.equal(eventTopicJoin.get("id"), eventTopicId)));
            systemSubscriptionRegistry = s.createQuery(criteriaQuery).getSingleResult();

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

        return systemSubscriptionRegistry;
    }

    @Override
    public List<SystemSubscription> getByTopic(long eventTopicId) {
        List<SystemSubscription> list;

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

            list = getByTopic(s, eventTopicId);

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

        return list;
    }

    @Override
    public List<SystemSubscription> getByTopic(Session s, long eventTopicId) {
        CriteriaBuilder builder = s.getCriteriaBuilder();
        CriteriaQuery<SystemSubscription> criteriaQuery = builder.createQuery(SystemSubscription.class);
        Root<SystemSubscription> root = criteriaQuery.from(SystemSubscription.class);
        Join<SystemSubscription, EventTopic> eventTopicJoin = root.join("eventTopic");
        criteriaQuery.where(builder.equal(eventTopicJoin.get("id"), eventTopicId));
        return s.createQuery(criteriaQuery).getResultList();
    }

    @Override
    public List<SystemSubscription> getByTopicAndType(long eventTopicId, SubscriptionType type) {
        List<SystemSubscription> list;

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

            CriteriaBuilder builder = s.getCriteriaBuilder();
            CriteriaQuery<SystemSubscription> criteriaQuery = builder.createQuery(SystemSubscription.class);
            Root<SystemSubscription> root = criteriaQuery.from(SystemSubscription.class);
            Join<SystemSubscription, EventTopic> eventTopicJoin = root.join("eventTopic");
            criteriaQuery.where(builder.and(
                    builder.equal(root.get("type"), type),
                    builder.equal(eventTopicJoin.get("id"), eventTopicId)));
            list = s.createQuery(criteriaQuery).getResultList();

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

        return list;
    }

    @Override
    public List<SystemSubscription> getByType(SubscriptionType type) {
        List<SystemSubscription> list;

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

            CriteriaBuilder builder = s.getCriteriaBuilder();
            CriteriaQuery<SystemSubscription> criteriaQuery = builder.createQuery(SystemSubscription.class);
            Root<SystemSubscription> root = criteriaQuery.from(SystemSubscription.class);
            criteriaQuery.where(builder.equal(root.get("type"), type));
            list = s.createQuery(criteriaQuery).getResultList();

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

        return list;
    }

    @Override
    public SystemSubscription add(SystemSubscription systemSubscriptionRegistry) throws IllegalAccessException {
        try (Session s = getSession()) {
            s.getTransaction().begin();
            if (!permissionService.existByAllParameters(
                    systemSubscriptionRegistry.getEventTopic().getId(),
                    PermissionConstants.TYPE_EVENT_TOPIC,
                    String.valueOf(systemSubscriptionRegistry.getSystem().getId()),
                    PermissionConstants.TYPE_SYSTEM,
                    PermissionConstants.ACTION_SUBSCRIBE)) {
                throw new IllegalAccessException("No permission to subscribe");
            }

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

        return systemSubscriptionRegistry;
    }

    @Override
    public SystemSubscription add(System system, EventTopic eventTopic, SubscriptionType type) throws IllegalAccessException {
        SystemSubscription systemSubscriptionRegistry = new SystemSubscription();

        systemSubscriptionRegistry.setSystem(system);
        systemSubscriptionRegistry.setEventTopic(eventTopic);
        systemSubscriptionRegistry.setType(type);

        return add(systemSubscriptionRegistry);
    }

    @Override
    public SystemSubscription update(SystemSubscription systemSubscriptionRegistry) {
        try (Session s = getSession()) {
            s.getTransaction().begin();
            s.merge(systemSubscriptionRegistry);
            s.getTransaction().commit();
            s.close();
        }

        return systemSubscriptionRegistry;
    }

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

            SystemSubscription systemSubscriptionRegistry = get(id);
            s.delete(SystemSubscription.class.getName(), systemSubscriptionRegistry);

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

    @Override
    public void removeByTopic(long eventTopicId) {
        try (Session s = getSession()) {
            s.getTransaction().begin();
            removeByTopic(s, eventTopicId);
            s.getTransaction().commit();
            s.close();
        }
    }

    @Override
    public void removeByTopic(Session s, long eventTopicId) {
        List<SystemSubscription> subscriptions = getByTopic(s, eventTopicId);
        subscriptions.forEach(s::delete);
    }

    @Override
    public void markAsDeleted(long id, boolean deleted) {
        try (Session s = getSession()) {
            SystemSubscription systemSubscription = get(id);
            s.getTransaction().begin();
            systemSubscription.setDeleted(deleted);
            s.update(systemSubscription);
            s.getTransaction().commit();
            s.close();
        }

    }

    @Override
    public void markAsDeletedByTopic(long eventTopicId, boolean deleted) {
        try (Session s = getSession()) {
            s.getTransaction().begin();
            markAsDeletedByTopic(s, eventTopicId, deleted);
            s.getTransaction().commit();
            s.close();
        }
    }

    @Override
    public void markAsDeletedByTopic(Session s, long eventTopicId, boolean deleted) {
        List<SystemSubscription> subscriptions = getByTopic(s, eventTopicId);
        subscriptions.forEach(subscription -> this.markAsDeletedProc(s, subscription, deleted));
    }

    private void markAsDeletedProc(Session s, SystemSubscription subscription, boolean deleted) {
        subscription.setDeleted(deleted);
        s.update(subscription);
    }

}
