/*-
 * ~~~~~~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.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import ru.entaxy.esb.system.core.events.jpa.EventTopicService;
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.permission.common.PermissionConstants;
import ru.entaxy.esb.system.core.permission.jpa.PermissionService;

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

public class EventTopicServiceImpl implements EventTopicService {

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

    private SessionFactory sessionFactory;
    private PermissionService permissionService;
    private SystemSubscriptionService systemSubscriptionService;

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

    public SystemSubscriptionService getSystemSubscriptionService() {
        return systemSubscriptionService;
    }

    public void setSystemSubscriptionService(SystemSubscriptionService systemSubscriptionService) {
        this.systemSubscriptionService = systemSubscriptionService;
    }

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

        return list;
    }

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

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

            CriteriaBuilder builder = s.getCriteriaBuilder();
            CriteriaQuery<EventTopic> cq = s.getCriteriaBuilder().createQuery(EventTopic.class);
            Root<EventTopic> root = cq.from(EventTopic.class);
            cq.where(builder.equal(root.get("deleted"), deleted));

            list = s.createQuery(cq).getResultList();
            s.getTransaction().commit();
            s.close();
        }

        return list;
    }

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

            Query<EventTopic> query = prepareQueryGet(s, id);
            eventTopic = query.getSingleResult();

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

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

            Query<EventTopic> query = prepareQueryGet(s, id);
            eventTopic = query.uniqueResultOptional();

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

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

    @Override
    public EventTopic getByName(String name) {
        EventTopic eventTopic;
        try (Session s = getSession()) {
            s.getTransaction().begin();

            Query<EventTopic> query = prepareQueryGetByName(s, name);
            eventTopic = query.getSingleResult();

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

    @Override
    public Optional<EventTopic> fetchByName(String name) {
        Optional<EventTopic> eventTopic;
        try (Session s = getSession()) {
            s.getTransaction().begin();

            Query<EventTopic> query = prepareQueryGetByName(s, name);
            eventTopic = query.uniqueResultOptional();

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

    private Query<EventTopic> prepareQueryGetByName(Session s, String name) {
        CriteriaBuilder builder = s.getCriteriaBuilder();
        CriteriaQuery<EventTopic> criteriaQuery = builder.createQuery(EventTopic.class);
        Root<EventTopic> root = criteriaQuery.from(EventTopic.class);
        criteriaQuery.where(builder.equal(root.get("name"), name));
        return s.createQuery(criteriaQuery);
    }

    @Override
    public EventTopic getByNameAndDeleted(String name, boolean deleted) {
        EventTopic eventTopic;
        try (Session s = getSession()) {
            s.getTransaction().begin();

            Query<EventTopic> query = prepareQueryGetByNameAndDeleted(s, name, deleted);
            eventTopic = query.getSingleResult();

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

    @Override
    public Optional<EventTopic> fetchByNameAndDeleted(String name, boolean deleted) {
        Optional<EventTopic> eventTopic;
        try (Session s = getSession()) {
            s.getTransaction().begin();

            Query<EventTopic> query = prepareQueryGetByNameAndDeleted(s, name, deleted);
            eventTopic = query.uniqueResultOptional();

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

    private Query<EventTopic> prepareQueryGetByNameAndDeleted(Session s, String name, boolean deleted) {
        CriteriaBuilder builder = s.getCriteriaBuilder();
        CriteriaQuery<EventTopic> criteriaQuery = builder.createQuery(EventTopic.class);
        Root<EventTopic> root = criteriaQuery.from(EventTopic.class);
        criteriaQuery.where(builder.and(
                builder.equal(root.get("name"), name),
                builder.equal(root.get("deleted"), deleted)
        ));
        return s.createQuery(criteriaQuery);
    }

    @Override
    public EventTopic add(EventTopic eventTopic) {
        try (Session s = getSession()) {
            s.getTransaction().begin();
            s.persist(eventTopic);
            s.getTransaction().commit();
            s.close();
        }
        return eventTopic;
    }

    @Override
    public EventTopic add(String name, String createdBy) {
        EventTopic eventTopic = new EventTopic();
        eventTopic.setName(name);
        eventTopic.setCreateDate(new Date());
        eventTopic.setCreatedBy(createdBy);

        return add(eventTopic);
    }

    @Override
    public EventTopic update(EventTopic eventTopic) {
        Optional<EventTopic> topicOldOpt = fetch(eventTopic.getId());
        return save(eventTopic, topicOldOpt.isPresent());
    }

    @Override
    public EventTopic update(long id, String name, String editedBy) {
        EventTopic eventTopic = get(id);
        fillModel(eventTopic, name, eventTopic.getCreateDate(), eventTopic.getCreatedBy(), new Date(), editedBy);
        return save(eventTopic, true);
    }

    private void fillModel(EventTopic eventTopic, String name, Date createDate,
                           String createdBy, Date editDate, String editedBy) {
        eventTopic.setName(name);
        eventTopic.setCreateDate(createDate);
        eventTopic.setCreatedBy(createdBy);
        eventTopic.setEditDate(editDate);
        eventTopic.setEditedBy(editedBy);
    }

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

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

            processRemove(s, eventTopic);

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

    }

    private void processRemove(Session s, EventTopic eventTopic) {
        permissionService.removeAll(s, eventTopic.getId(), PermissionConstants.TYPE_EVENT_TOPIC);
        s.flush();
        systemSubscriptionService.removeByTopic(s, eventTopic.getId());
        s.flush();
        s.delete(EventTopic.class.getName(), eventTopic);
    }

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

            EventTopic eventTopic = get(id);

            processRemove(s, eventTopic);

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

    @Override
    public void markAsDeleted(long id, boolean deleted) {
        try (Session s = getSession()) {
            s.getTransaction().begin();

            EventTopic eventTopic = get(id);

            systemSubscriptionService.markAsDeletedByTopic(s, eventTopic.getId(), deleted);
            s.flush();

            eventTopic.setDeleted(deleted);
            s.update(eventTopic);

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

    @Override
    public int clean() {
        List<EventTopic> listToDelete = listByDeleted(true);

        listToDelete.forEach(t -> remove(t));

        return listToDelete.size();
    }


}
