package com.munjaon.client.config;

import jakarta.annotation.PostConstruct;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.ConfigurationBuilderEvent;
import org.apache.commons.configuration2.builder.ReloadingFileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Parameters;
import org.apache.commons.configuration2.event.Event;
import org.apache.commons.configuration2.event.EventListener;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.configuration2.reloading.PeriodicReloadingTrigger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class ServerConfig {
    @Getter
//    @Value("${agent.server-property-file}")
    private String serverProperyFile;

    @Getter
    @Value("${agent.root-path}")
    private String serverRootPath;

    private ReloadingFileBasedConfigurationBuilder<PropertiesConfiguration> builder;

    @PostConstruct
    void init() throws ConfigurationException {
//        this.serverRootPath = System.getProperty("SERVICE_HOME");
        this.serverProperyFile = serverRootPath + File.separator + "config" + File.separator + "munjaonAgent.conf";
        builder = new ReloadingFileBasedConfigurationBuilder<>(PropertiesConfiguration.class).configure(new Parameters().fileBased().setFile(new File(serverProperyFile)));

        builder.addEventListener(ConfigurationBuilderEvent.CONFIGURATION_REQUEST, new EventListener<Event>() {
            @Override
            public void onEvent(Event event) {
                log.info("builder.getConfiguration() is Called!!");
            }
        });

        PeriodicReloadingTrigger configReloadingTrigger = new PeriodicReloadingTrigger(builder.getReloadingController(), null, 1, TimeUnit.SECONDS);
        configReloadingTrigger.start();
    }

    public String getString(String key) throws ConfigurationException {
        return builder.getConfiguration().getString(key);
    }

    public int getInt(String key) throws ConfigurationException {
        return builder.getConfiguration().getInt(key, 3);
    }

    public String[] getStringArray(String key) throws ConfigurationException {
        return getStringArray(key, ",");
    }

    public String[] getStringArray(String key, String regExp) throws ConfigurationException {
        String value = getString(key);
        return value == null ? null : value.split(regExp);
    }
}
