package src.fr.impl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Optional;

import src.fr.api.Part;


public class HtmlGenerator {
    
    static final String HEADER = "<!DOCTYPE html><html><head><title>Cartailor</title><style></style></head>\n";

    static private String generateStringHTML(ConfigurationImpl config){
        String header ="<!DOCTYPE html>\n<html>\n<head>\n<title>Cartailor</title>\n";
        header += "<style>\n";
        header += "table{border-collapse: collapse;}\n";
        header +="th,td{border: 1px solid rgb(160 160 160);padding: 8px 10px;}";
        header += "</style>\n";
        header += "</head>\n";

        String body = "<body>\n";
        body += "\t<table>\n";
        for(Part pt: config.getSelectedParts()){
            body += "\t\t<tr>\n";

            body+= "\t\t\t<th>" + pt.getType().getCategory().getName() + "</th>\n";
            body+= "\t\t\t<th>" + pt.getType().getName() + "</th>\n";
            body+= "\t\t\t<th>" + ((PartImpl)pt).getPrice() + " €</th>\n";
            for(String pr: pt.getPropertyNames()){
                Optional<String> prOptional = pt.getProperty(pr);
                if(!prOptional.isEmpty()){
                    body+= "\t\t\t<th>" + pr + " : " + prOptional.get() + "</th>\n";
                }
            }

            body += "\t\t</tr>\n";
        
        }
        body += "\t\t<tr>\n";
        body += "\t\t\t<th colspan=\"2\">Total Price : </th>\n";
        body += "\t\t\t<th>" + config.getTotalPrice() + " € </th>\n";
        body += "\t\t</tr>\n";

        body += "\t</table>\n";




        body += "</body>\n";
        return header + body + "</html>";
    }

    static public void generateHTML(ConfigurationImpl config) throws IOException{
        if(config.isValid()){
            String content = generateStringHTML(config);
            
            String projectRoot = System.getProperty("user.dir");
            File file = new File(projectRoot, "cartailor.html");

            try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
                writer.write(content);
            }
            System.out.println(projectRoot+"\\cartailor.html");
        }
    }
}
