// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
package booking;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import java.util.stream.Collectors;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class SwingGui extends JFrame {
    private static final long serialVersionUID = 1L;
    private static final String DATA_PROVIDER_NAME = "booking.DummyDataProvider";
    private DataProvider data;
    private JTextArea bookings;
    private JComboBox<Hotel> hotels;
    private void handleException(Exception e) {
        JOptionPane.showMessageDialog(null, e.toString());
        System.exit(1);
    }
    public SwingGui() {
        try {
            data = (DataProvider)Class.forName(DATA_PROVIDER_NAME).newInstance();
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            handleException(e);
        }
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent event) {
                data.close(SwingGui.this::handleException);
                SwingGui.this.dispose();
                System.exit(0);
            }
        });
        setTitle("Booking System");
        setLayout(new BorderLayout());
        bookings = new JTextArea();
        bookings.setPreferredSize(new Dimension(400,400));
        add(bookings, BorderLayout.CENTER);
        hotels = new JComboBox<>(data.getHotelList(this::handleException).toArray(new Hotel[0]));
        hotels.addActionListener(evt -> fillBookings());
        add(hotels, BorderLayout.NORTH);
        pack();
    }
    public void fillBookings() {
        Hotel h = (Hotel)hotels.getSelectedItem();
        List<Booking> blst = data.getBookingList(h.getName(), this::handleException);
        bookings.setText(blst.stream().map(b -> b.toString()).collect(Collectors.joining("\r\n")));
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame f = new SwingGui();
                f.setVisible(true);
            }
        });
    }
}
