package eu.eudat.logic.utilities.documents.xml;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import eu.eudat.logic.services.forms.VisibilityRuleService;
import eu.eudat.logic.utilities.builders.XmlBuilder;
import eu.eudat.models.data.components.commons.datafield.ExternalDatasetsData;
import eu.eudat.models.data.user.components.datasetprofile.Field;
import eu.eudat.models.data.user.components.datasetprofile.FieldSet;
import eu.eudat.models.data.user.components.datasetprofile.Section;
import eu.eudat.models.data.user.composite.DatasetProfilePage;
import eu.eudat.models.data.user.composite.PagedDatasetProfile;
import org.json.JSONArray;
import org.json.JSONException;
import org.springframework.core.env.Environment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class ExportXmlBuilder {

    public File build(PagedDatasetProfile pagedDatasetProfile, UUID datasetProfileId, VisibilityRuleService visibilityRuleService, Environment environment) throws IOException {

        File xmlFile = new File(environment.getProperty("temp.temp") + UUID.randomUUID() + ".xml");
        BufferedWriter writer = new BufferedWriter(new FileWriter(xmlFile, true));
        Document xmlDoc = XmlBuilder.getDocument();
        Element root = xmlDoc.createElement("root");
        Element datasetProfile = xmlDoc.createElement("datasetProfileId");
        datasetProfile.setTextContent(datasetProfileId.toString());
        root.appendChild(datasetProfile);
        root.appendChild(createPages(pagedDatasetProfile.getPages(), visibilityRuleService, xmlDoc));
        xmlDoc.appendChild(root);
        String xml = XmlBuilder.generateXml(xmlDoc);
        writer.write(xml);
        writer.close();
        return xmlFile;
    }

    public Element createPages(List<DatasetProfilePage> datasetProfilePages, VisibilityRuleService visibilityRuleService, Document element) {
        Element pages = element.createElement("pages");
        datasetProfilePages.forEach(item -> {
            Element page = element.createElement("page");
            page.appendChild(createSections(item.getSections(), visibilityRuleService, element));
            pages.appendChild(page);
        });
        return pages;
    }

    private Element createSections(List<Section> sections, VisibilityRuleService visibilityRuleService, Document element) {
        Element elementSections = element.createElement("sections");
        sections.forEach(section -> {
            Element elementSection = element.createElement("section");
            if (visibilityRuleService.isElementVisible(section.getId())) {
                elementSection.appendChild(createSections(section.getSections(), visibilityRuleService, element));
                elementSection.appendChild(createCompositeFields(section.getCompositeFields(), visibilityRuleService, element));
                elementSections.appendChild(elementSection);
            }
        });
        return elementSections;
    }

    private Element createCompositeFields(List<FieldSet> compositeFields, VisibilityRuleService visibilityRuleService, Document element) {
        Element elementComposites = element.createElement("composite-fields");
        compositeFields.forEach(compositeField -> {
            if (visibilityRuleService.isElementVisible(compositeField.getId()) && hasVisibleFields(compositeField, visibilityRuleService)) {
                Element composite = element.createElement("composite-field");
                composite.setAttribute("id", compositeField.getId());
                if (compositeField.getTitle() != null && !compositeField.getTitle().isEmpty()) {
                    Element title = element.createElement("title");
                    title.setTextContent(compositeField.getTitle());
                    composite.appendChild(title);
                }
                if (compositeField.getDescription() != null && !compositeField.getDescription().isEmpty()) {
                    Element title = element.createElement("description");
                    title.setTextContent(compositeField.getDescription());
                    composite.appendChild(title);
                }
                composite.appendChild(createFields(compositeField.getFields(), visibilityRuleService, element));
                elementComposites.appendChild(composite);

            }
        });
        return elementComposites;
    }

    private Element createFields(List<Field> fields, VisibilityRuleService visibilityRuleService, Document element) {
        Element elementFields = element.createElement("fields");
        fields.forEach(field -> {
            if (visibilityRuleService.isElementVisible(field.getId())) {
                Element elementField = element.createElement("field");
                elementField.setAttribute("id", field.getId());
                if (field.getViewStyle().getRenderStyle().equals("externalDatasets")) {
                    elementField.setAttribute("type", ((ExternalDatasetsData)field.getData()).getType());
                }
                if (field.getValue() != null) {
                    Element valueField = element.createElement("value");
                    ObjectMapper mapper = new ObjectMapper();
                    try {

                        List<Map<String, Object>> jsonArray = mapper.readValue(field.getValue().toString(), List.class);
//                        JSONArray jsonArray = new JSONArray(field.getValue().toString());
                        StringBuilder sb = new StringBuilder();
                        boolean firstTime = true;
                        for (Map<String, Object> jsonElement: jsonArray) {
                            if (!firstTime) {
                                sb.append(", ");
                            }
                            sb.append(jsonElement.get("label") != null ? jsonElement.get("label") : jsonElement.get("name"));
                            firstTime = false;

                        }
                        /*for (int i = 0; i < jsonArray.length(); i++) {
                            sb.append(jsonArray.getJSONObject(i).get("label").toString());
                            if (i != jsonArray.length() - 1) sb.append(", ");
                        }*/
                        valueField.setTextContent(sb.toString());
                    } catch (IOException ex) {
                        try {
                            Map<String, Object> jsonElement = mapper.readValue(field.getValue().toString(), Map.class);
                            valueField.setTextContent((jsonElement.get("label") != null ? jsonElement.get("label").toString() : jsonElement.get("name") != null ? jsonElement.get("name").toString() : ""));
                        } catch (IOException e) {
                            try {
                                valueField.setTextContent(DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneId.systemDefault()).format(Instant.parse(field.getValue().toString())));
                            } catch (Exception exc) {
                                valueField.setTextContent(field.getValue().toString());
                            }
                        }
                    }
                    elementField.appendChild(valueField);
                }
                elementFields.appendChild(elementField);
            }
        });
        return elementFields;
    }

    private boolean hasVisibleFields(FieldSet compositeFields, VisibilityRuleService visibilityRuleService) {
        return compositeFields.getFields().stream().anyMatch(field -> visibilityRuleService.isElementVisible(field.getId()));
    }
}
