package com.onsemi.middleware.camel.karavan;

import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.spi.RoutesBuilderLoader;
import org.apache.camel.spi.Resource;
import org.apache.camel.dsl.yaml.YamlRoutesBuilderLoader;
import org.apache.camel.support.ResourceHelper;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.FileWriter;


public class YamlLoaderIsolationTest {

    @Test
    public void testLoadYamlRouteFromFile() throws Exception {
        String yamlContent = """
- route:
    id: route-26d1
    nodePrefixId: route-93e
    from:
      id: from-9d21
      uri: kamelet:oracle-database-source
      parameters:
        serverName: xxxxxxxxxxxxxxxx
        serverPort: xxxxxxxxxxxxxxxx
        password: xxxxxxxxxxxxxxxx
        query: SELECT id, name, status FROM interfaces_mr WHERE processed IS NULL
        consumedQuery: UPDATE interfaces_mr SET processed = 1 WHERE id = :#id
        databaseName: xxxxxxxxxxxxxxxxx
        username: xxxxxxxxxxxx
      steps:
        - to:
            id: to-3437
            uri: kamelet:oracle-database-sink
            parameters:
              username:
              query: INSERT INTO interfaces_mr2 (id, name, status, created_at, processed) VALUES (:#ID, :#NAME, :#STATUS, SYSDATE, 1)
              password: xxxxxxxxxxxxxxxx
              databaseName: xxxxxxxxxxxxxxxx
              serverPort: xxxxxxxxxxxxxxxx
              serverName: xxxxxxxxxxxxxxxx
""";


        File yamlFile = File.createTempFile("camel-route", ".yaml");


        FileWriter writer = new FileWriter(yamlFile);
        writer.write(yamlContent);
        writer.flush();
        writer.close();
        yamlFile.deleteOnExit();
        CamelContext camelCtx = new DefaultCamelContext();


        RoutesBuilderLoader yamlLoader = new YamlRoutesBuilderLoader();
        yamlLoader.setCamelContext(camelCtx);

        Resource yamlResource = ResourceHelper.resolveResource(camelCtx, "file:" + yamlFile.getAbsolutePath());
        RouteBuilder builder = (RouteBuilder) yamlLoader.loadRoutesBuilder(yamlResource);
        camelCtx.addRoutes(builder);

        camelCtx.start();
        Thread.sleep(2000);

        camelCtx.stop();
    }
}