import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;

public class LockerGui extends JFrame implements ActionListener {

    //Declare GUI Components
    private JTextField txtStudentID;
    private JLabel lblStudentID;
    private JButton btnAssign;
    private JComboBox<Integer> cboLockerNumbers;
    private JTextArea txtAssignments;
    private LockerManager manager;

    public LockerGui() {
        //setup Frame
        setTitle("Locker Assignments");
        setSize(700, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());
        JPanel topPanel = new JPanel(new GridLayout(1, 1));
        Integer[] lockerNums = {1,2,3,4,5,6,7,8,9,10};
        //initialise components
        txtStudentID = new JTextField();
        lblStudentID = new JLabel("Enter student id:");
        btnAssign = new JButton("Assign Locker");
        cboLockerNumbers = new JComboBox<>(lockerNums);
        manager = new LockerManager();

        //add actionListener to the button
        btnAssign.addActionListener(this);

        //add components to the topPanel
        topPanel.add(lblStudentID);
        topPanel.add(txtStudentID);
        topPanel.add(cboLockerNumbers);
        topPanel.add(btnAssign);

        //add topPanel to the frame
        add(topPanel, BorderLayout.NORTH);

        //create panel to display assignments
        JPanel centerPanel = new JPanel();
        txtAssignments = new JTextArea();
        centerPanel.add(txtAssignments);

        //add the panel to the frame
        add(centerPanel, BorderLayout.SOUTH);


        //make the frame visible
        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e){
        if(e.getSource().equals(btnAssign)){
            String id = txtStudentID.getText();
            int lockerNum = (int) cboLockerNumbers.getSelectedItem();
            manager.assignLocker(id, lockerNum);
            refreshLists();
        }
    }

    public void refreshLists(){
        HashMap<String, Integer> map = manager.getLockers();
        txtAssignments.setText("");

        String txt = "";
        for(String key : map.keySet()){
            txt += key + ":" + map.get(key)+"\n";
        }

        txtAssignments.append(txt+"\n");



    }
}
