/**
 * Use a JFrame window that accept a last name
 * Search an address book for that lastname
 * Get result and display in the window
 *
 * This layout uses a FlowLayout Manager
 */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class AddrBookView1 extends JFrame implements ActionListener, AddrBookView 
{
    private AddrBookControl control;            //A reference to the control object
    private String searchStr;                   //The last name to search for

    JLabel      lastnameLbl = new JLabel("Enter Lastname: ");
    JTextField  lastname    = new JTextField(22);
    JButton     search      = new JButton("Search");
    JTextArea   result      = new JTextArea(10, 22);    //height, width
    JScrollPane result2     = new JScrollPane(result);  //make it scrollable


    AddrBookView1(AddrBookControl c)                  	//constructor
    {
        this.control = c;
    }

    public void getUserInput()                          //Called by controller object            
    {
        setTitle("Address Book");                       //set title       
        setDefaultCloseOperation(EXIT_ON_CLOSE);        //action when click on X
        setSize(280, 300);

        Container panel = getContentPane();             //get reference to the content pane

        FlowLayout layout = new FlowLayout();           //create a FlowLayout manager
        panel.setLayout(layout);                        //Flow the window using layout

        result.setEditable(false);                      //cannot edit results

        panel.add(lastnameLbl);                         //add components to window
        panel.add(lastname);
        panel.add(search);
        panel.add(result2);

        setVisible(true);                               //make window visible

        search.addActionListener(this);                 //add an event handler on button
    }


    public void actionPerformed(ActionEvent evt)
    {
        String lname  = lastname.getText();             //get test from window
 
        control.search(lname);              //call the controller search method
    } 


    public void display(AddrBookEntry[] entry, int numMatches, String msg)    //Called by the controller object
    {       
        String str = msg + "\n";

        if (numMatches == 1)                    //if one entry was found
            str = "";                           //no need to display number of matches
                
        for (int i=0; i<numMatches; i++)        //loop and create a proper display
            str += entry[i] + "\n";
                    
        result.setText(str);                    //place formatted text in window                
        result.setCaretPosition(0);             //scroll back to top
    }
}