package projetMusee.backend.reports;

import projetMusee.backend.Museum;

import java.util.List;
import java.util.Map;
import java.util.function.Function;

public class HTMLReportGenerator {

    private static final Map<String, Function<Museum, String>> ATTRIBUTE_EXTRACTORS = Map.of(
            "Nom", Museum::getOfficialName,
            "Adresse", Museum::getAddress,
            "Ville", Museum::getCity,
            "Département", Museum::getDepartment,
            "Région", Museum::getRegion,
            "Thème", Museum::getThemes,
            "AnnéeCréation", m -> String.valueOf(m.getCreationYear()),
            "CodePostal", Museum::getPostalCode,
            "Categorie", Museum::getCategory,
            "URL", Museum::getUrl);

    public static String generateHTML(List<Museum> filteredMuseums, List<String> selectedAttributes) {
        StringBuilder html = new StringBuilder();

        html.append("<html><head><style>")
                .append("table { width: 100%; border-collapse: collapse; }")
                .append("th, td { border: 1px solid #ccc; padding: 8px; text-align: left; }")
                .append("th { background-color: #f2f2f2; }")
                .append("</style></head><body>");

        html.append("<h2>Rapport des musées filtrés</h2>");
        html.append("<table><tr>");
        for (String attr : selectedAttributes) {
            html.append("<th>").append(attr).append("</th>");
        }
        html.append("</tr>");

        for (Museum museum : filteredMuseums) {
            html.append("<tr>");
            for (String attr : selectedAttributes) {
                String value = ATTRIBUTE_EXTRACTORS.containsKey(attr)
                        ? ATTRIBUTE_EXTRACTORS.get(attr).apply(museum)
                        : "N/A";
                html.append("<td>").append(escapeHTML(value)).append("</td>");
            }
            html.append("</tr>");
        }

        html.append("</table></body></html>");
        return html.toString();
    }

    private static String escapeHTML(String input) {
        if (input == null)
            return "";
        return input.replace("&", "&amp;")
                .replace("<", "&lt;")
                .replace(">", "&gt;")
                .replace("\"", "&quot;")
                .replace("'", "&#39;");
    }
}
