/*-
 * ~~~~~~licensing~~~~~~
 * system-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.jpa.impl;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import ru.entaxy.esb.system.jpa.SystemService;
import ru.entaxy.esb.system.jpa.entity.ExportAllowed;
import ru.entaxy.esb.system.jpa.entity.System;
import ru.entaxy.esb.system.management.bundle.jpa.entity.BundleEntity;

import javax.persistence.EntityGraph;
import javax.persistence.TypedQuery;
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;
import java.util.Set;

public class SystemServiceImpl implements SystemService {

    private static final String JAVAX_PERSISTENCE_LOADGRAPH = "javax.persistence.loadgraph";
    private static final String SYSTEM_ENTITY_GRAPH = "system-entity-graph";
    private SessionFactory sessionFactory;

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

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

    @Override
    public List<System> getSystemList() {
        List<System> list;
        try (Session session = getSession()) {
            session.getTransaction().begin();
            CriteriaQuery<System> criteriaQuery = session.getCriteriaBuilder().createQuery(System.class);
            Root<System> root = criteriaQuery.from(System.class);
            criteriaQuery.select(root);
            list = session.createQuery(criteriaQuery).getResultList();
            session.getTransaction().commit();
        }
        return list;
    }

    @Override
    public List<System> getFullSystemListByOriginIsEmpty() {
        List<System> list;
        try (Session session = getSession()) {
            session.getTransaction().begin();
            EntityGraph entityGraph = session.getEntityGraph(SYSTEM_ENTITY_GRAPH);
            CriteriaQuery<System> criteriaQuery = session.getCriteriaBuilder().createQuery(System.class);
            Root<System> root = criteriaQuery.from(System.class);
            criteriaQuery.select(root);
            criteriaQuery.where(session.getCriteriaBuilder().isNull(root.get("origin")));
            TypedQuery<System> typedQuery = session.createQuery(criteriaQuery);
            typedQuery.setHint(JAVAX_PERSISTENCE_LOADGRAPH, entityGraph);
            list = typedQuery.getResultList();
            session.getTransaction().commit();
        }
        return list;
    }

    @Override
    public List<System> getFullSystemListByPermissionBySubject(String uuid) {
        List<System> list;
        try (Session session = getSession()) {
            session.getTransaction().begin();
            EntityGraph entityGraph = session.getEntityGraph(SYSTEM_ENTITY_GRAPH);
            Query query = session.createQuery("SELECT DISTINCT session" +
                    " from System session " +
                    " join Permission p on p.objectId = session.id" +
                    " join System s1 on p.subjectId =  cast(s1.id as string)" +
                    " where s1.uuid = :uuid");

            query.setParameter("uuid", uuid);
            query.setHint(JAVAX_PERSISTENCE_LOADGRAPH, entityGraph);

            list = query.getResultList();
            session.getTransaction().commit();
        }
        return list;
    }

    @Override
    public List<System> getFullSystemListByPermissionByObject(String uuid) {
        List<System> list;
        try (Session session = getSession()) {
            session.getTransaction().begin();
            EntityGraph entityGraph = session.getEntityGraph(SYSTEM_ENTITY_GRAPH);
            Query query = session.createQuery("SELECT DISTINCT session" +
                    " from System session " +
                    " join Permission p on p.subjectId = cast(session.id as string)" +
                    " join System s1 on p.objectId = s1.id" +
                    " where s1.uuid = :uuid");

            query.setParameter("uuid", uuid);
            query.setHint(JAVAX_PERSISTENCE_LOADGRAPH, entityGraph);

            list = query.getResultList();
            session.getTransaction().commit();
        }
        return list;
    }

    @Override
    public List<System> getFullSystemListByNotOrigin() {
        List<System> list;
        try (Session session = getSession()) {
            session.getTransaction().begin();
            EntityGraph entityGraph = session.getEntityGraph(SYSTEM_ENTITY_GRAPH);
            CriteriaQuery<System> criteriaQuery = session.getCriteriaBuilder().createQuery(System.class);
            Root<System> root = criteriaQuery.from(System.class);
            criteriaQuery.select(root);
            criteriaQuery.where(session.getCriteriaBuilder().isNotNull(root.get("origin")));
            TypedQuery<System> typedQuery = session.createQuery(criteriaQuery);
            typedQuery.setHint(JAVAX_PERSISTENCE_LOADGRAPH, entityGraph);
            list = typedQuery.getResultList();
            session.getTransaction().commit();
        }

        return list;
    }

    @Override
    public System get(long id) {
        System system;
        try (Session session = getSession()) {
            session.getTransaction().begin();

            EntityGraph entityGraph = session.getEntityGraph(SYSTEM_ENTITY_GRAPH);
            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<System> criteriaQuery = builder.createQuery(System.class);
            Root<System> root = criteriaQuery.from(System.class);
            criteriaQuery.where(builder.equal(root.get("id"), id));
            TypedQuery<System> typedQuery = session.createQuery(criteriaQuery);
            typedQuery.setHint(JAVAX_PERSISTENCE_LOADGRAPH, entityGraph);
            system = typedQuery.getSingleResult();

            session.getTransaction().commit();
        }
        return system;
    }

    @Override
    public System getByUuid(String uuid) {
        System system;
        try (Session session = getSession()) {
            session.getTransaction().begin();

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<System> criteriaQuery = builder.createQuery(System.class);
            Root<System> root = criteriaQuery.from(System.class);
            criteriaQuery.where(builder.equal(root.get("uuid"), uuid));
            system = session.createQuery(criteriaQuery).getSingleResult();

            session.getTransaction().commit();
        }
        return system;
    }

    @Override
    public System getByName(String name) {
        System system;
        try (Session session = getSession()) {
            session.getTransaction().begin();

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<System> criteriaQuery = builder.createQuery(System.class);
            Root<System> root = criteriaQuery.from(System.class);
            criteriaQuery.where(builder.equal(root.get("name"), name));
            system = session.createQuery(criteriaQuery).getSingleResult();

            session.getTransaction().commit();
        }
        return system;
    }


    @Override
    public Optional<System> fetch(long id) {
        Optional<System> system;
        try (Session session = getSession()) {
            session.getTransaction().begin();

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<System> criteriaQuery = builder.createQuery(System.class);
            Root<System> root = criteriaQuery.from(System.class);
            criteriaQuery.where(builder.equal(root.get("id"), id));
            system = session.createQuery(criteriaQuery).uniqueResultOptional();

            session.getTransaction().commit();
        }
        return system;
    }

    @Override
    public Optional<System> fetchByUuid(String uuid) {
        Optional<System> system;
        try (Session session = getSession()) {
            session.getTransaction().begin();

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<System> criteriaQuery = builder.createQuery(System.class);
            Root<System> root = criteriaQuery.from(System.class);
            criteriaQuery.where(builder.equal(root.get("uuid"), uuid));
            system = session.createQuery(criteriaQuery).uniqueResultOptional();

            session.getTransaction().commit();
        }
        return system;
    }

    @Override
    public Optional<System> fetchByName(String name) {
        Optional<System> system;
        try (Session session = getSession()) {
            session.getTransaction().begin();

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<System> criteriaQuery = builder.createQuery(System.class);
            Root<System> root = criteriaQuery.from(System.class);
            criteriaQuery.where(builder.equal(root.get("name"), name));
            system = session.createQuery(criteriaQuery).uniqueResultOptional();

            session.getTransaction().commit();
        }
        return system;
    }

    @Override
    public System setBundleEntity(System system, BundleEntity bundleEntity) {
        BundleEntity origin = system.getBundleEntity();
        if (origin != null) {
        	origin.setUrl(bundleEntity.getUrl());
            origin.setStatus(bundleEntity.getStatus());
        } else {
            bundleEntity.setVersion(system.getVersion());
            system.setBundleEntity(bundleEntity);
        }
        return this.saveOrUpdate(system);
    }

    @Override
    public ExportAllowed addExportAllowed(System system, String exportAllowedName) {
        ExportAllowed exportAllowed = getExportAllowed(system.getExportAllowed(), exportAllowedName);
        if (exportAllowed == null) {
            exportAllowed = new ExportAllowed();
            exportAllowed.setName(exportAllowedName);
            system.getExportAllowed().add(exportAllowed);
            saveOrUpdate(system);
        }
        return exportAllowed;
    }

    @Override
    public System create(System system) {
        Optional<System> original = fetchByUuid(system.getUuid());
        if (original.isPresent()) {
            original.get().setDescription(system.getDescription());
            original.get().setEditDate(system.getCreateDate());
            original.get().setEditedBy(system.getCreatedBy());
        }
        return this.saveOrUpdate(original.orElse(system));
    }

    @Override
    public System saveOrUpdate(System system) {
        try (Session session = getSession()) {
            session.getTransaction().begin();
            session.saveOrUpdate(system);
            session.getTransaction().commit();
        }
        return system;
    }

    @Override
    public System saveOrUpdate(String systemName, String uuid, String description, Date createDate,
                               Date editDate, String createdBy, String editedBy,
                               String version, String type) {
        System system = new System();
        system.setUuid(uuid);
        system.setName(systemName);
        system.setDescription(description);
        system.setCreateDate(createDate);
        system.setCreatedBy(createdBy);
        system.setEditDate(editDate);
        system.setEditedBy(editedBy);
        system.setVersion(version);
        system.setType(type);

        return this.saveOrUpdate(system);
    }

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

            System system = get(id);
            session.delete(System.class.getName(), system);

            session.getTransaction().commit();
        }
    }

    @Override
    public void remove(System system) {
        try (Session session = getSession()) {
            session.getTransaction().begin();

            session.delete(System.class.getName(), system);

            session.getTransaction().commit();
        }
    }

    @Override
    public void removeExportAllowed(System system, String esbName) {
        try (Session session = getSession()) {
            session.getTransaction().begin();

            ExportAllowed exportAllowed = getExportAllowed(system.getExportAllowed(), esbName);
            session.delete(ExportAllowed.class.getName(), exportAllowed);

            session.getTransaction().commit();
        }
    }

    private ExportAllowed getExportAllowed(Set<ExportAllowed> exportAllowedSet, String exportAllowedName) {
        for (ExportAllowed allowed : exportAllowedSet) {
            if (allowed.getName().equals(exportAllowedName)) {
                return allowed;
            }
        }
        return null;
    }
}
