/* BdfServer - Copyright (c) 2021-2025 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 fr.exemole.bdfserver.tools.storage;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import net.mapeadores.util.html.HA;
import net.mapeadores.util.html.HtmlAttributes;
import net.mapeadores.util.io.ResourceStorages;
import net.mapeadores.util.mimetype.MimeTypeResolver;
import net.mapeadores.util.text.FileName;
import net.mapeadores.util.text.RelativePath;


/**
 *
 * @author Vincent Calame
 */
public final class IconScanEngine {

    public final static String ICON_PREFIX = "icon-";
    public final static String APPLETOUCHICON_PREFIX = "touchicon-";
    public final static String SHORTCUTICON_PREFIX = "shortcuticon-";
    public final static RelativePath ICON_FOLDER = RelativePath.build("images");


    private IconScanEngine() {

    }

    public static List<HtmlAttributes> run(ResourceStorages resourceStorages, MimeTypeResolver mimeTypeResolver) {
        SortedMap<String, RelativePath> resources = resourceStorages.listResources(ICON_FOLDER, false);
        List<HtmlAttributes> result = new ArrayList<HtmlAttributes>();
        for (String name : resources.keySet()) {
            try {
                FileName fileName = FileName.parse(name);
                HtmlAttributes htmlAttributes = toHtmlAttributes(fileName, mimeTypeResolver);
                if (htmlAttributes != null) {
                    result.add(htmlAttributes);
                }
            } catch (ParseException pe) {

            }
        }
        return result;
    }

    private static HtmlAttributes toHtmlAttributes(FileName fileName, MimeTypeResolver mimeTypeResolver) {
        String baseName = fileName.getBasename();
        String sizes;
        String rel;
        if (baseName.startsWith(ICON_PREFIX)) {
            sizes = baseName.substring(ICON_PREFIX.length());
            rel = "icon";
        } else if (baseName.startsWith(APPLETOUCHICON_PREFIX)) {
            sizes = baseName.substring(APPLETOUCHICON_PREFIX.length());
            rel = "apple-touch-icon";
        } else if (baseName.startsWith(SHORTCUTICON_PREFIX)) {
            sizes = baseName.substring(SHORTCUTICON_PREFIX.length());
            rel = "shortcut icon";
        } else {
            return null;
        }
        sizes = sizes.replace('_', ' ');
        String mimeType = mimeTypeResolver.getMimeType(fileName.getExtension());
        return HA.href(ICON_FOLDER.buildChild(fileName.toString()).toString()).rel(rel).type(mimeType).attr("sizes", sizes);
    }


}
