/*-
 * ~~~~~~licensing~~~~~~
 * schema-component
 * ==========
 * 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.platform.runtime.core.infrastructure.schema.component;

import org.apache.camel.Component;
import org.apache.camel.Consumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.camel.spi.UriPath;
import org.apache.camel.support.DefaultEndpoint;
import org.osgi.framework.FrameworkUtil;
import org.w3c.dom.ls.LSResourceResolver;

import ru.entaxy.esb.platform.runtime.core.infrastructure.schema.api.ResourceService;
import ru.entaxy.esb.platform.runtime.core.infrastructure.schema.component.util.SchemaReaderFromDB;
import ru.entaxy.platform.base.support.osgi.OSGIUtils;

@UriEndpoint(
        scheme = "validatorWithDBStorage",
        title = "ValidatorWithDBStorage",
        syntax = "validatorWithDBStorage:namespace",
        label = "Custom validator component with loader resources from db",
        producerOnly = true)
public class ValidatorWithDBStorageEndpoint extends DefaultEndpoint {

    @UriPath(description = "URL to a local resource on the classpath, or a reference to lookup a bean in the Registry,"
            + " or a full URL to a remote resource or resource on the file system which contains the XSD to validate against.")
    @Metadata(required = true)
    private String uri;

    @UriParam(description = "Version")
    @Metadata(required = true)
    private String version;
    /**
     * We need a one-to-one relation between endpoint and schema reader in order to be able to clear
     * the cached schema in the schema reader. See method
     */
    private final SchemaReaderFromDB schemaReaderFromDB;
    private volatile boolean schemaReaderConfigured;

    private ResourceService resourceService;
    private LSResourceResolver resourceResolver;

    public ValidatorWithDBStorageEndpoint(String uri, Component component) {
        super(uri, component);
        this.uri = uri.replace("validatorWithDBStorage://", "").replace("validatorWithDBStorage:", "")
                .replace("validatorWithDBStorage", "");
        schemaReaderFromDB = this.uri.isEmpty() ? new SchemaReaderFromDB()
                : new SchemaReaderFromDB(getCamelContext(), this.uri, version);
    }

    public Producer createProducer() throws Exception {
        if (!schemaReaderConfigured) {
            if (resourceResolver != null) {
                schemaReaderFromDB.setResourceResolver(getResourceResolver());
            }

            schemaReaderFromDB.setResourceService(getResourceService());
            // force loading of schema at create time otherwise concurrent
            // processing could cause thread safe issues for the
            // javax.xml.validation.SchemaFactory
            schemaReaderFromDB.loadSchema();

            // configure only once
            schemaReaderConfigured = true;
        }

        ValidatingProcessor validator = new ValidatingProcessor(schemaReaderFromDB, uri);
        return new ValidatorWithDBStorageProducer(this, validator);
    }

    public Consumer createConsumer(Processor processor) throws Exception {
        return null;
    }

    public boolean isSingleton() {
        return true;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public ResourceService getResourceService() {
        if (resourceService == null) {
            resourceService = (ResourceService) OSGIUtils.getService(
                    FrameworkUtil.getBundle(ValidatorWithDBStorageEndpoint.class).getBundleContext(),
                    ResourceService.class);
        }
        return resourceService;
    }

    private LSResourceResolver getResourceResolver() {
        if (resourceResolver == null) {
            resourceResolver = (LSResourceResolver) OSGIUtils.getService(
                    FrameworkUtil.getBundle(ValidatorWithDBStorageEndpoint.class).getBundleContext(),
                    LSResourceResolver.class);
        }
        return resourceResolver;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getVersion() {
        return version;
    }
}
