/*
 * 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.SingleSelectionModel;
import com.arsdigita.bebop.Table;
import com.arsdigita.bebop.PageState;
import com.arsdigita.formbuilder.PersistentFormSection;
import java.math.BigDecimal;
import com.arsdigita.bebop.table.TableModel;
import java.util.Iterator;
import com.arsdigita.formbuilder.PersistentProcessListener;
import com.arsdigita.domain.DataObjectNotFoundException;
import com.arsdigita.bebop.table.AbstractTableModelBuilder;
import com.arsdigita.util.UncheckedWrapperException;



public class ProcessListenerTableModelBuilder extends AbstractTableModelBuilder {
    SingleSelectionModel m_selection;

    public ProcessListenerTableModelBuilder(SingleSelectionModel selection) {
        m_selection = selection;
    }

    public TableModel makeModel(Table table,
                                PageState state) {
        PersistentFormSection form = null;
        try {
            form = new PersistentFormSection((BigDecimal)m_selection.getSelectedKey(state));
        } catch (DataObjectNotFoundException ex) {
            ex.printStackTrace();
            throw new UncheckedWrapperException(ex);
        }

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

    private class PersistentFormTableModel implements TableModel {
        private Iterator m_listeners;
        private PersistentProcessListener listener;

        public PersistentFormTableModel(Iterator listeners) {
            m_listeners = listeners;
        }


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

        public int getColumnCount() {
            return 3;
        }

        public Object getKeyAt(int columnIndex) {
            return listener.getID();
        }

        public Object getElementAt(int columnIndex) {
            return listener;
        }
    }
}
