package eu.eudat.models.data.entities.xmlmodels.datasetprofiledefinition;

import eu.eudat.logic.utilities.builders.XmlBuilder;
import eu.eudat.logic.utilities.interfaces.XmlSerializable;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.util.LinkedList;
import java.util.List;

public class ViewStyleModel implements XmlSerializable<ViewStyleModel> {
    private List<Section> sections;
    private List<Page> pages;

    public List<Section> getSections() {
        return sections;
    }

    public void setSections(List<Section> sections) {
        this.sections = sections;
    }

    public List<Page> getPages() {
        return pages;
    }

    public void setPages(List<Page> pages) {
        this.pages = pages;
    }

    @Override
    public Element toXml(Document doc) {
        Element root = doc.createElement("root");
        Element sections = doc.createElement("sections");
        Element pages = doc.createElement("pages");
        for (Section section : this.sections) {
            section.setNumbering("" + (this.sections.indexOf(section) + 1));
            sections.appendChild(section.toXml(doc));
        }

        for (Page page : this.pages) {
            pages.appendChild(page.toXml(doc));
        }

        root.appendChild(pages);
        root.appendChild(sections);
        return root;
    }

    @Override
    public ViewStyleModel fromXml(Element element) {

        this.sections = new LinkedList();
        Element sections = (Element) XmlBuilder.getNodeFromListByTagName(element.getChildNodes(), "sections");
        if (sections != null) {
            NodeList sectionElements = sections.getChildNodes();
            for (int temp = 0; temp < sectionElements.getLength(); temp++) {
                Node sectionElement = sectionElements.item(temp);
                if (sectionElement.getNodeType() == Node.ELEMENT_NODE) {
                    this.sections.add(new Section().fromXml((Element) sectionElement));
                }
            }
        }
        this.pages = new LinkedList<>();
        Element pages = (Element) XmlBuilder.getNodeFromListByTagName(element.getChildNodes(), "pages");
        if (pages != null) {
            NodeList pagesElements = pages.getChildNodes();
            for (int temp = 0; temp < pagesElements.getLength(); temp++) {
                Node pageElement = pagesElements.item(temp);
                if (pageElement.getNodeType() == Node.ELEMENT_NODE) {
                    this.pages.add(new Page().fromXml((Element) pageElement));
                }
            }
        }
        return this;
    }


}
