/*
 * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the
 * License at http://www.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.formbuilder.ui;


import com.arsdigita.bebop.List;
import com.arsdigita.bebop.list.ListModel;
import com.arsdigita.bebop.list.ListModelBuilder;
import com.arsdigita.bebop.PageState;

import com.arsdigita.bebop.parameters.IntegerParameter;

import com.arsdigita.domain.DataObjectNotFoundException;

import com.arsdigita.formbuilder.PersistentFormSection;
import com.arsdigita.formbuilder.PersistentProcessListener;


import com.arsdigita.util.LockableImpl;
import com.arsdigita.util.UncheckedWrapperException;

import java.math.BigDecimal;

import java.util.Iterator;


public class ProcessListenerListModelBuilder extends LockableImpl implements ListModelBuilder {
    public ListModel makeModel(List l, PageState state) {
        Integer form_id = (Integer)state.getValue(new IntegerParameter("form"));
        PersistentFormSection form = null;
        try {
            form = new PersistentFormSection(new BigDecimal(form_id.intValue()));
        } catch (DataObjectNotFoundException ex) {
            throw new UncheckedWrapperException(ex);
        }

        return new ProcessListenerListModel(form.getProcessListeners());
    }

    private class ProcessListenerListModel implements ListModel {
        private Iterator m_listeners;
        private PersistentProcessListener listener;

        public ProcessListenerListModel(Iterator listeners) {
            m_listeners = listeners;
            listener = null;
        }

        public boolean next() {
            if (m_listeners.hasNext()) {
                listener = (PersistentProcessListener)m_listeners.next();
                return true;
            }
            return false;
        }

        public Object getElement() {
            return listener;
        }

        public String getKey() {
            return listener.getID().toString();
        }
    }
}
