/* BdfServer - Copyright (c) 2019 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.ActionEntry;
import fr.exemole.bdfserver.api.menu.ActionGroup;
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 ActionGroupBuilder {

    private final String id;
    private final List<ActionEntry> entryList = new ArrayList<ActionEntry>();
    private Object titleObject;

    public ActionGroupBuilder(String id) {
        if (id == null) {
            throw new NullPointerException("id is null");
        }
        this.id = id;
    }

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

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

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

    public ActionGroupBuilder addActionEntry(ActionEntry actionEntry) {
        entryList.add(actionEntry);
        return this;
    }

    public boolean isEmpty() {
        return entryList.isEmpty();
    }

    public ActionGroup toActionGroup() {
        Object finalTitleObject = titleObject;
        if (finalTitleObject == null) {
            finalTitleObject = id;
        }
        List<ActionEntry> finalList = MenuUtils.wrap(entryList.toArray(new ActionEntry[entryList.size()]));
        return new InternalActionGroup(id, finalTitleObject, finalList);
    }

    public static ActionGroupBuilder init(String id) {
        return new ActionGroupBuilder(id);
    }


    private static class InternalActionGroup implements ActionGroup {

        private final String id;
        private final Object title;
        private final List<ActionEntry> actionEntryList;

        private InternalActionGroup(String id, Object title, List<ActionEntry> actionEntryList) {
            this.id = id;
            this.title = title;
            this.actionEntryList = actionEntryList;
        }

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

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

        @Override
        public List<ActionEntry> getActionEntryList() {
            return actionEntryList;
        }

    }

}
