/*-
 * ~~~~~~licensing~~~~~~
 * schema-component
 * ==========
 * Copyright (C) 2020 - 2021 EmDev LLC
 * ==========
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.esb.system.registry.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.system.common.osgi.OSGIUtils;
import ru.entaxy.esb.system.registry.schema.api.ResourceService;
import ru.entaxy.esb.system.registry.schema.component.util.SchemaReaderFromDB;

@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.getServiceReference(
                    FrameworkUtil.getBundle(ValidatorWithDBStorageEndpoint.class).getBundleContext(),
                    ResourceService.class.getName());
        }
        return resourceService;
    }

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

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

    public String getVersion() {
        return version;
    }
}
