package com.eactive.httpmockserver.common.message;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PortalReloadableResourceBundleMessageSource extends org.springframework.context.support.ReloadableResourceBundleMessageSource {
    private static final String CLASSPATH_PREFIX = "classpath:";
    private static final String PROPERTIES_EXTENSION = ".properties";

    private final ResourcePatternResolver resourcePatternResolver;

    public PortalReloadableResourceBundleMessageSource() {
        this.resourcePatternResolver = new PathMatchingResourcePatternResolver();
    }

    public void setEgovBaseNames(String... basenames) {
        List<String> resolvedBasenames = new ArrayList<>();
        for (String basename : basenames) {
            String trimmedBasename = StringUtils.trimToEmpty(basename);
            if (trimmedBasename.startsWith(CLASSPATH_PREFIX)) {
                resolvedBasenames.add(trimmedBasename);
            } else if (StringUtils.isNotBlank(trimmedBasename)) {
                try {
                    Resource[] resources = resourcePatternResolver.getResources(trimmedBasename);
                    for (Resource resource : resources) {
                        String uri = resource.getURI().toString();
                        if (!uri.contains(PROPERTIES_EXTENSION)) {
                            continue;
                        }
                        String baseName = processBasename(uri);
                        resolvedBasenames.add(baseName);
                    }
                } catch (IOException e) {
                    logger.debug("No message source files found for basename " + trimmedBasename + ".");
                }
            }
        }
        setBasenames(resolvedBasenames.toArray(new String[0]));
    }

    private String processBasename(String uri) {
        String baseName = StringUtils.substringBeforeLast(uri, PROPERTIES_EXTENSION);
        String prefix = StringUtils.substringBeforeLast(baseName, "/");
        String name = StringUtils.substringAfterLast(baseName, "/");
        while (name.contains("_")) {
            name = StringUtils.substringBeforeLast(name, "_");
        }
        return prefix + "/" + name;
    }
}
