
package org.openspml.browser;

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

// avoid awt conflict
import java.util.List;


import org.openspml.util.*;
import org.openspml.message.*;

public class SearchPanel extends RequestPanel {

    JTextField _searchBase;
    JTextField _filter;
    JTextField _attributes;
    JTable _results;
    SearchInstaller _installer;

    public SearchPanel(State s) {
        super(s);
        _installer = new SearchInstaller();

        addRequestIdPanel();

        _searchBase = new JTextField(25);
        _searchBase.addActionListener(this);
        _form.add("Search Base", _searchBase);

        _filter = new JTextField(25);
        _filter.addActionListener(this);
        _form.add("Filter", _filter);

        _attributes = new JTextField(25);
        _attributes.addActionListener(this);
        _form.add("Attributes", _attributes);

        addSubmitButton();

        _results = new JTable();
        JScrollPane sp = new JScrollPane();
        SwingUtil.add(sp, _results);
        _tabs.add(sp, "Response Table");
    }

    public Installer getInstaller() {
        return _installer;
    }

    public SpmlRequest getRequest() {

        SearchRequest req = new SearchRequest();
        req.setRequestId(_reqid.getRequestId());
        req.setAsynchronous(_reqid.isAsync());

        req.setSearchBase(SwingUtil.getText(_searchBase));

        String atts = SwingUtil.getText(_attributes);
        if (atts != null)
            req.setAttributes(Util.decodeCommaString(atts));

        String text = SwingUtil.getText(_filter);
        if (text != null) {
            try {
                Parser p = new Parser();
                Filter f = p.parseFilter(text);
                if (f != null)
                    req.setFilter(f);
            }
            catch (Throwable t) {
                SwingUtil.displayError(t);
                req = null;
            }
        }

        return req;
    }

    /**
     * Handler eventually called via State.doRequest in the Swing
     * event thread to install a response into the GUI.
     */
    private class SearchInstaller extends Installer {

        public void install(SpmlResponse response) {

            SearchResponse sr = (SearchResponse)response;

            refreshResponse(response);

            _results.setModel(new SearchTableModel(sr));
            _tabs.setSelectedIndex(2);
        }
    }

}
