package com.onsemi.middleware.camel.karavan

import com.onsemi.middleware.UECommon.model.InterfaceJcaps
import com.onsemi.middleware.camel.context.KaravanPropertySource
import spock.lang.Specification
import java.nio.file.Files
import java.nio.file.Path

class KaravanPropertySourceTest extends Specification {

    def "should load properties from application.properties"() {
        given: "a temporary directory with application.properties file"
        Path tempDir = Files.createTempDirectory("karavan-test")
        Path interfaceDir = tempDir.resolve("TestInterface")
        Files.createDirectory(interfaceDir)
        Path propertiesFile = interfaceDir.resolve("application.properties")

        Properties props = new Properties()
        props.setProperty("some.key", "someValue")
        props.setProperty("another.key", "anotherValue")
        props.store(Files.newOutputStream(propertiesFile), null)

        and:
        InterfaceJcaps interfaceJcaps = Mock()
        interfaceJcaps.getName() >> "TestInterface"

        when:
        def propertySource = new KaravanPropertySource(interfaceJcaps, tempDir.toString())

        then:
        propertySource.getProperties().size() == 2
        propertySource.getProperty("some.key") == "someValue"
        propertySource.getProperty("another.key") == "anotherValue"
    }

    def "should return submap with keys containing substring"() {
        given:
        InterfaceJcaps interfaceJcaps = Mock()
        interfaceJcaps.getName() >> "DummyInterface"
        def karavanSource = new KaravanPropertySource(interfaceJcaps, System.getProperty("java.io.tmpdir"))
        karavanSource.getProperties().putAll([
                "db.username": "admin",
                "db.password": "secret",
                "api.key": "xyz123"
        ])

        when:
        def subMap = karavanSource.getPropertySubMap("db")

        then:
        subMap.size() == 2
        subMap["db.username"] == "admin"
        subMap["db.password"] == "secret"
    }

    def "setProperty should replace existing property value"() {
        given:
        InterfaceJcaps interfaceJcaps = Mock()
        interfaceJcaps.getName() >> "DummyInterface"
        def karavanSource = new KaravanPropertySource(interfaceJcaps, System.getProperty("java.io.tmpdir"))
        karavanSource.getProperties().put("config.name", "oldValue")

        when:
        karavanSource.setProperty("config.name", "newValue")

        then:
        karavanSource.getProperty("config.name") == "newValue"
    }

}
