/* BdfServer - Copyright (c) 2012-2018 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.menu;

import fr.exemole.bdfserver.api.menu.MenuGroup;
import fr.exemole.bdfserver.api.menu.MenuNode;
import java.util.ArrayList;
import java.util.List;
import net.mapeadores.util.localisation.LocalisationUtils;
import net.mapeadores.util.localisation.Message;


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

    private final String id;
    private final List<MenuNode> menuNodeList = new ArrayList<MenuNode>();
    private String title;
    private Message titleMessage;

    public MenuGroupBuilder(String id) {
        this.id = id;
    }

    public MenuGroupBuilder(String id, String title) {
        this.id = id;
        this.title = title;
    }

    public MenuGroupBuilder setTitle(String title) {
        this.title = title;
        return this;
    }

    public MenuGroupBuilder setTitleMessage(Message titleMessage) {
        this.titleMessage = titleMessage;
        return this;
    }

    public MenuGroupBuilder setTitleMessage(String messageKey, Object... messageValues) {
        this.titleMessage = LocalisationUtils.toMessage(messageKey, messageValues);
        return this;
    }

    public MenuGroupBuilder addMenuNode(MenuNode menuNode) {
        menuNodeList.add(menuNode);
        return this;
    }

    public MenuGroup toMenuGroup() {
        String finalTitle = title;
        if (finalTitle == null) {
            if (titleMessage != null) {
                finalTitle = titleMessage.getMessageKey();
            } else {
                finalTitle = "";
            }
        }
        List<MenuNode> list = MenuUtils.wrap(menuNodeList.toArray(new MenuNode[menuNodeList.size()]));
        return new InternalMenuGroup(id, finalTitle, titleMessage, list);
    }


    private static class InternalMenuGroup implements MenuGroup {

        private final String id;
        private final String title;
        private final Message titleMessage;
        private final List<MenuNode> list;

        private InternalMenuGroup(String id, String title, Message titleMessage, List<MenuNode> list) {
            this.id = id;
            this.title = title;
            this.titleMessage = titleMessage;
            this.list = list;
        }

        @Override
        public String getId() {
            return id;
        }

        @Override
        public Message getTitleMessage() {
            return titleMessage;
        }

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

        @Override
        public List<MenuNode> getMenuNodeList() {
            return list;
        }

    }

}
