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

import com.sun.istack.NotNull;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import ru.entaxy.esb.system.connector.entity.Connector;
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.Join;
import javax.persistence.criteria.Root;
import java.util.List;

public class ConnectorServiceImpl implements ConnectorService {

    private static final String JAVAX_PERSISTENCE_LOADGRAPH = "javax.persistence.loadgraph";
    private static final String CONNECTOR_ENTITY_GRAPH = "connector-entity-graph";

    private SessionFactory sessionFactory;

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

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

    @Override
    public Connector getConnectorByName(String name) {
        Connector connector;
        try (Session session = getSession()) {
            session.getTransaction().begin();

            EntityGraph entityGraph = session.getEntityGraph(CONNECTOR_ENTITY_GRAPH);
            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<Connector> criteriaQuery = builder.createQuery(Connector.class);
            Root<Connector> root = criteriaQuery.from(Connector.class);
            criteriaQuery.where(builder.equal(root.get("name"), name));

            TypedQuery<Connector> typedQuery = session.createQuery(criteriaQuery);
            typedQuery.setHint(JAVAX_PERSISTENCE_LOADGRAPH, entityGraph);
            connector = typedQuery.getSingleResult();

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

    @Override
    public Connector getConnectorByName(String systemUuid, String templateName) {
        Connector connector;
        try (Session session = getSession()) {
            session.getTransaction().begin();

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<Connector> criteriaQuery = builder.createQuery(Connector.class);

            Root<System> root = criteriaQuery.from(System.class);
            Join<System, Connector> connectorJoin = root.join("connectors");

            criteriaQuery.select(connectorJoin);
            criteriaQuery.where(builder.and(builder.equal(root.get("uuid"), systemUuid),
                    builder.equal(connectorJoin.get("templateName"), templateName)));

            connector = session.createQuery(criteriaQuery).getSingleResult();

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

    @Override
    public void removeConnector(@NotNull Connector connector) {
        try (Session session = getSession()) {
            session.getTransaction().begin();

            session.delete(Connector.class.getName(), connector);

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

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

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

    @Override
    public Connector addConnector(System system, Connector connector) {
        Connector connectorEntity = getConnector(system, connector.getTemplateName());
        if (connectorEntity == null) {
            connectorEntity = connector;
            connectorEntity.setName(connector.getTemplateName() + "." + system.getName());
            connectorEntity.setSystemId(system.getId());
            system.getConnectors().add(connectorEntity);
        } else {
            connectorEntity.setEditDate(connector.getCreateDate());
            connectorEntity.setEditedBy(connector.getCreatedBy());
        }
        this.saveOrUpdate(system);
        return connectorEntity;
    }

    @Override
    public Connector addNewConnector(System system, Connector connector) {
        Connector connectorEntity = getNewConnector(system, connector.getName());
        if (connectorEntity == null) {
            connectorEntity = connector;
            connectorEntity.setSystemId(system.getId());
            system.getConnectors().add(connectorEntity);
        } else {
            connectorEntity.setEditDate(connector.getCreateDate());
            connectorEntity.setEditedBy(connector.getCreatedBy());
        }
        this.saveOrUpdate(system);
        return connectorEntity;
    }

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

    @Override
    public List<Connector> getListConnector() {
        List<Connector> list;
        try (Session session = getSession()) {
            session.getTransaction().begin();
            EntityGraph entityGraph = session.getEntityGraph(CONNECTOR_ENTITY_GRAPH);
            CriteriaQuery<Connector> criteriaQuery = session.getCriteriaBuilder().createQuery(Connector.class);
            criteriaQuery.from(Connector.class);
            TypedQuery<Connector> typedQuery = session.createQuery(criteriaQuery);
            typedQuery.setHint(JAVAX_PERSISTENCE_LOADGRAPH, entityGraph);
            list = typedQuery.getResultList();
            session.getTransaction().commit();
        }

        return list;
    }

    private Connector getConnector(System system, String templateName) {
        for (Connector connector : system.getConnectors()) {
            if (templateName.equals(connector.getTemplateName()))
                return connector;
        }
        return null;
    }

    private Connector getNewConnector(System system, String name) {
        for (Connector connector : system.getConnectors()) {
            if (name.equals(connector.getName()))
                return connector;
        }
        return null;
    }
}
