package org.openautonomousconnection.webserver.runtime;

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

/**
 * Caches compiled Java WebPages by file lastModified timestamp.
 */
public final class JavaPageCache {

    private static final class Entry {
        final long lastModified;
        final Class<?> clazz;

        Entry(long lastModified, Class<?> clazz) {
            this.lastModified = lastModified;
            this.clazz = clazz;
        }
    }

    private final ConcurrentHashMap<String, Entry> cache = new ConcurrentHashMap<>();

    public Class<?> getOrCompile(File javaFile) throws Exception {
        String key = javaFile.getAbsolutePath();
        long lm = javaFile.lastModified();

        Entry e = cache.get(key);
        if (e != null && e.lastModified == lm) {
            return e.clazz;
        }

        Class<?> compiled = JavaPageCompiler.compile(javaFile);
        cache.put(key, new Entry(lm, compiled));
        return compiled;
    }
}
