package com.atlassian.stash.internal.plugin;

import com.atlassian.plugin.servlet.ContentTypeResolver;
import com.atlassian.plugin.spring.AvailableToPlugins;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import javax.activation.FileTypeMap;
import javax.activation.MimetypesFileTypeMap;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;

/**
 * A simple content type resolver that can identify css and js resources.
 */
@AvailableToPlugins(ContentTypeResolver.class)
@Component("contentTypeResolver")
public class SimpleContentTypeResolver implements ContentTypeResolver {

    private final FileTypeMap fileTypes;

    public SimpleContentTypeResolver() throws IOException {
        try (InputStream in = new ClassPathResource("mime.types").getInputStream()) {
            this.fileTypes = new MimetypesFileTypeMap(in);
        }
    }

    @Override
    public String getContentType(String requestUrl) {
        String filename = requestUrl.substring(requestUrl.lastIndexOf('/'));

        return fileTypes.getContentType(filename.toLowerCase(Locale.US));
    }
}
