package org.micord.utils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.micord.models.CachedConfig;
import org.micord.models.Requests;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author Maksim Tereshin
 */
@Component
public class ConfigLoader {

  private static final Logger LOGGER = Logger.getLogger(ConfigLoader.class.getName());
  private static final Map<String, CachedConfig> cachedConfigs = new ConcurrentHashMap<>();

  @Value("${configDirectory}")
  private String configDirectory;

  public Optional<Requests> loadConfigIfModified(String methodName) {
    String fileName = methodName + ".xml";

    if (configDirectory == null) {
      LOGGER.log(Level.SEVERE, "No configuration directory found for method: " + methodName);
      return Optional.empty();
    }

    try {
      File configFile = new File(configDirectory + File.separator + fileName);
      Path configFilePath = configFile.toPath();
      FileTime currentModifiedTime = Files.getLastModifiedTime(configFilePath);
      CachedConfig cachedConfig = cachedConfigs.getOrDefault(methodName, null);

      if (cachedConfig == null || !currentModifiedTime.equals(cachedConfig.getModifiedTime())) {
        // Load the updated configuration
        JAXBContext jaxbContext = JAXBContext.newInstance(Requests.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        Requests loadedConfig = (Requests) unmarshaller.unmarshal(configFile);
        cachedConfigs.put(methodName, new CachedConfig(loadedConfig, currentModifiedTime));
        return Optional.of(loadedConfig);
      }
      else {
        return Optional.of(cachedConfigs.get(methodName).getConfig());
      }

    }
    catch (IOException e) {
      LOGGER.log(Level.SEVERE, "Failed to load configuration file: " + fileName, e);
      return Optional.empty();  // Return empty if there is an IO error
    }
    catch (JAXBException e) {
      LOGGER.log(Level.SEVERE, "Failed to unmarshal configuration file: " + fileName, e);
      return Optional.empty();  // Return empty if unmarshalling fails
    }
  }
}
