/* BdfServer - Copyright (c) 2020 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package fr.exemole.bdfserver.tools.memento;

import fr.exemole.bdfserver.api.memento.MementoNode;
import java.util.ArrayList;
import java.util.List;


/**
 *
 * @author Vincent Calame
 */
public class MementoNodeBuilder {


    private final String name;
    private final List<MementoNode> subnodeList = new ArrayList<MementoNode>();
    private String title = "";
    private String text = "";

    public MementoNodeBuilder(String name) {
        this.name = name;
    }

    public MementoNodeBuilder setTitle(String title) {
        if (title == null) {
            this.title = "";
        } else {
            this.title = title;
        }
        return this;
    }

    public MementoNodeBuilder setText(String text) {
        if (text == null) {
            this.text = "";
        } else {
            this.text = text.trim();
        }
        return this;
    }

    public MementoNodeBuilder addSubnode(MementoNode subnode) {
        subnodeList.add(subnode);
        return this;
    }

    public MementoNode toMementoNode() {
        if (title.isEmpty()) {
            title = name;
        }
        List<MementoNode> finalList;
        if (subnodeList.isEmpty()) {
            finalList = MementoUtils.EMPTY_NODELIST;
        } else {
            finalList = MementoUtils.wrap(subnodeList.toArray(new MementoNode[subnodeList.size()]));
        }
        return new InternalMementoNode(name, title, finalList, text);
    }


    private static class InternalMementoNode implements MementoNode {

        private final String name;
        private final String title;
        private final List<MementoNode> mementoNodeList;
        private final String text;

        private InternalMementoNode(String name, String title, List<MementoNode> mementoNodeList, String text) {
            this.name = name;
            this.title = title;
            this.mementoNodeList = mementoNodeList;
            this.text = text;
        }

        @Override
        public String getName() {
            return name;
        }

        @Override
        public String getTitle() {
            return title;
        }

        @Override
        public boolean isLeaf() {
            return mementoNodeList.isEmpty();
        }

        @Override
        public List<MementoNode> getSubnodeList() {
            return mementoNodeList;
        }

        @Override
        public String getText() {
            return text;
        }

    }

}
