package com.crm.rely.backend.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WebPageFormUtil {

    private static final String formFixed = "<p>%s</p>\n" +
            "<table style=\"border-collapse: collapse; width: 99.8136%s;\" border=\"1\">\n" +
            "<tbody>\n" +
            "%s" +
            "</tbody>\n" +
            "</table>\n";

    private static final String columnFixed = "<tr>\n" +
            "%s" +
            "</tr>\n";
    private static final String lineFixed = "<td style=\"width: %.4f%s;\">%s</td>\n";

    private static final String explainFixed = "%s:%s<br />\n";

    public static String createWebPageForm(Map<String, String> explainMap, List<List<String>> forms) {

        String explain = createExplain(explainMap);
        String form = createForm(forms);

        return String.format(formFixed, explain, "%", form);
    }

    public static String createForm(List<List<String>> forms) {

        if (forms == null || forms.size() <= 0) {
            return "";
        }

        StringBuffer columnStringBuffer = new StringBuffer(forms.size());

        for (List<String> lines : forms) {
            int lineCount = lines.size();
            double lineWidth = 99.8136 / lineCount;

            StringBuffer lineStringBuffer = new StringBuffer(lineCount);
            for (String line : lines) {
                lineStringBuffer.append(String.format(lineFixed, lineWidth, "%", line));
            }

            columnStringBuffer.append(String.format(columnFixed, lineStringBuffer.toString()));
        }
        return columnStringBuffer.toString();
    }

    public static String createExplain(Map<String, String> explainMap) {

        if (explainMap == null || explainMap.size() <= 0) {
            return "";
        }

        StringBuffer explainStringBuffer = new StringBuffer(explainMap.size());

        for (Map.Entry<String, String> explainEntry : explainMap.entrySet()) {
            explainStringBuffer.append(String.format(explainFixed, explainEntry.getKey(), explainEntry.getValue()));
        }

        return explainStringBuffer.toString();
    }

    public static void main(String[] args) {

        Map<String, String> explainMap = new HashMap<>(5);
        explainMap.put("1", "aaaaaaaaaaa");
        explainMap.put("2", "bbbbbbbbbb");
        explainMap.put("3", "ccccccccccc");
        explainMap.put("4", "dddddddddddd");
        explainMap.put("5", "eeeeeeeeeeee");

        List<List<String>> columns = new ArrayList<>(5);
        for (int i = 0; i < 5; i++) {
            List<String> lines = new ArrayList<>(5);
            for (int j = 0; j < 5; j++) {
                lines.add("column:" + i + "line:" + j);
            }
            columns.add(lines);
        }
        System.out.println(createWebPageForm(explainMap,columns));
    }
}
