import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Vector;

public class toDoGUI extends JFrame implements ActionListener {
    private Collection<String> container = new ArrayList<>();
    private JList<String> myList = new JList<>();
    private JButton tasks;
    private JButton add;
    private JButton delete;

    public toDoGUI() {
        super("My to do list");
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setLayout(new BorderLayout());

        //Example
        container.add("Cooking");
        container.add("Calling Mum");
        container.add("Walking the Dog");
        updateList();

        //GUI Design
        JPanel buttons = new JPanel();
        buttons.setLayout(new BorderLayout());
        tasks = new JButton("Tasks");
        tasks.addActionListener(this);
        add = new JButton("Add task");
        add.addActionListener(this);
        delete = new JButton("Delete taks");
        delete.addActionListener(this);
        buttons.add(tasks, BorderLayout.NORTH);
        buttons.add(add, BorderLayout.CENTER);
        buttons.add(delete, BorderLayout.SOUTH);
        this.add(buttons, BorderLayout.WEST);
        this.add(myList, BorderLayout.EAST);

        pack();
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource().equals(add)) {
            String newEntry = JOptionPane.showInputDialog(this, "Enter a descriptive name for the new task", "Add task", JOptionPane.QUESTION_MESSAGE);
            if (newEntry != null) {
                container.add(newEntry);
                updateList();
            }
        } else if (e.getSource().equals(delete)) {
            String subject = myList.getSelectedValue();
            if (subject != null) {
                container.remove(subject);
                updateList();
            } else {
                JOptionPane.showMessageDialog(this, "No task selected", "Error", JOptionPane.ERROR_MESSAGE );
            }
        }
    }

    private void updateList() {
        Vector<String> v = new Vector<>() ;
        for (String s : container)
            v.add(s);
        myList.setListData(v);
    }

    public static void main(String[] args) {
        new toDoGUI();
    }
}
