package com.onsemi.middleware.camel.context;

import com.onsemi.middleware.UECommon.model.InterfaceJcaps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;

public class KaravanPropertySource{

    private static final Logger logger = LoggerFactory.getLogger(KaravanPropertySource.class);

    private final Map<String, String> properties = new HashMap<>();

    public KaravanPropertySource(InterfaceJcaps interfaceJcaps, String karavanYamlPath) {
        loadProperties(interfaceJcaps, karavanYamlPath);
    }

    public Map<String, String> getProperties() {
        return properties;
    }
    public String getProperty(String name) {
        return properties.get(name);
    }

    public String setProperty(String name, String value){
        properties.replace(name, value);
        return name;
    }
    public HashMap<String, String> getPropertySubMap(String keyValue) {
        return properties.entrySet()
                .stream()
                .filter(entry -> entry.getKey().toLowerCase().contains(keyValue.toLowerCase()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, HashMap::new));
    }

    private void loadProperties(InterfaceJcaps interfaceJcaps, String karavanYamlPath) {
        String propertiesFilePath = Paths.get(karavanYamlPath, interfaceJcaps.getName(), "application.properties").toString();

        try (FileInputStream fis = new FileInputStream(propertiesFilePath)) {
            Properties props = new Properties();
            props.load(fis);
            for (String key : props.stringPropertyNames()) {
                properties.put(key, props.getProperty(key));
            }
            logger.info("Loaded properties: {}", properties);
        } catch (IOException e) {
            logger.error("Failed to load properties file: {}", propertiesFilePath, e);
        }
    }
}