/* UtilLib - Copyright (c) 2012-2017 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package net.mapeadores.util.mimetype;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import net.mapeadores.util.exceptions.InternalResourceException;


/**
 *
 * @author Vincent Calame
 */
public final class MimeTypeUtils implements MimeTypeConstants {

    public final static MimeTypeResolver DEFAULT_RESOLVER = initDefault();

    private MimeTypeUtils() {
    }

    public static String getMimeType(MimeTypeResolver mimeTypeResolver, String fileName) {
        int idx = fileName.lastIndexOf('.');
        if (idx == -1) {
            return MimeTypeConstants.OCTETSTREAM;
        }
        String extension = fileName.substring(idx + 1);
        return mimeTypeResolver.getMimeType(extension);
    }

    /**
     * Retourne UTF-8 s'il s'agit d'un fichier que l'on peut traiter comme du
     * texte null sinon
     */
    public static String getDefaultCharset(String mimeType) {
        if (mimeType.startsWith("text/")) {
            return "UTF-8";
        }
        if (mimeType.contains("xml")) {
            return "UTF-8";
        }
        if (mimeType.equals(MimeTypeConstants.JAVASCRIPT)) {
            return "UTF-8";
        }
        if (mimeType.equals(MimeTypeConstants.JSON)) {
            return "UTF-8";
        }
        return null;
    }

    private static MimeTypeResolver initDefault() {
        MimeTypeResolverBuilder builder = new MimeTypeResolverBuilder();
        try (Reader reader = new InputStreamReader(MimeTypeUtils.class.getResourceAsStream("utillib-list.txt"), "UTF-8")) {
            builder.parse(reader);
        } catch (IOException ioe) {
            throw new InternalResourceException(ioe);
        }
        try (Reader reader = new InputStreamReader(MimeTypeUtils.class.getResourceAsStream("debian-list.txt"), "UTF-8")) {
            builder.parse(reader);
        } catch (IOException ioe) {
            throw new InternalResourceException(ioe);
        }
        return builder.toMimeTypeResolver();
    }

}
