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

import eu.eudat.logic.utilities.builders.XmlBuilder;

import eu.eudat.models.data.entities.xmlmodels.dmpprofiledefinition.DataManagementPlanProfile;
import eu.eudat.models.data.listingmodels.DataManagementPlanProfileListingModel;
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.util.UUID;

public class ExportXmlBuilderDmpProfile {


    public File build(DataManagementPlanProfileListingModel dmpProfile, 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 definition = xmlDoc.createElement("definition");
//        Element root = xmlDoc.createElement(dmpProfile.getLabel());
        definition.appendChild(createDefinition(dmpProfile.getDefinition(), xmlDoc));
        root.appendChild(definition);
        xmlDoc.appendChild(root);
        String xml = XmlBuilder.generateXml(xmlDoc);
        writer.write(xml);
        writer.close();
        return xmlFile;
    }

    public Element createDefinition(DataManagementPlanProfile dmpDefinition, Document element) {
        Element fields = element.createElement("fieldSets");
        dmpDefinition.getFields().forEach(item -> {
            Element field = element.createElement("field");
            field.setAttribute("id", "" + item.getId());
            field.setAttribute("type", "" + item.getType());
            field.setAttribute("dataType", "" + item.getDataType());
            field.setAttribute("required", "" + item.getRequired());
            field.setAttribute("label", "" + item.getLabel());
            if(item.getValue()!=null) {
                Element value = element.createElement("value");
                value.setAttribute("value", ""+item.getValue());
                field.appendChild(value);
            }
            fields.appendChild(field);
        });
        return fields;
    }

}
