import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class CommandJPanel extends JPanel implements ActionListener {
	private static final long serialVersionUID = 1L;
	private static final Font titleFont = new Font(new JLabel().getFont().getName(), Font.BOLD, 14);

	private JButton addPattern;
	private JButton editPattern;
	private JButton removePattern;
	private JButton exports;
	private JButton imports;
	
	private Interface interf;

	public CommandJPanel(Interface interf) {
		this.interf = interf;
		setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
		setBorder(BorderFactory.createMatteBorder(0, 4, 0, 0, Color.LIGHT_GRAY));
		
		// Title
		
		JLabel title = new JLabel("Commands :");
		title.setFont(titleFont);
		add(title);
		
		// Buttons
		
		addPattern = new JButton("Add pattern");
		editPattern = new JButton("Edit pattern");
		removePattern = new JButton("Remove pattern");
		exports = new JButton("Export");
		imports = new JButton("Import");

		addPattern.setMaximumSize(removePattern.getMaximumSize());
		editPattern.setMaximumSize(removePattern.getMaximumSize());
		exports.setMaximumSize(removePattern.getMaximumSize());
		imports.setMaximumSize(removePattern.getMaximumSize());

		addPattern.addActionListener(this);
		editPattern.addActionListener(this);
		removePattern.addActionListener(this);
		exports.addActionListener(this);
		imports.addActionListener(this);
		
		add(addPattern);
		add(editPattern);
		add(removePattern);
		add(exports);
		add(imports);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == addPattern) {
			PatternEditorJDialog dialog = new PatternEditorJDialog(interf);
			Music music = dialog.showDialog();
			if(music == null)
				return;
			interf.musicList.addMusic(music);
			interf.timeLinePanel.updateList();
		} else if(e.getSource() == editPattern) {
			int index = interf.timeLineList.getSelectedIndex();
			if(index == -1)
				return;
			PatternEditorJDialog dialog = new PatternEditorJDialog(interf, interf.musicList.getList().get(index));
			Music music = dialog.showDialog();
			if(music == null)
				return;
			interf.musicList.setMusicAt(index, music);
			interf.timeLinePanel.updateList();
		} else if(e.getSource() == removePattern) {
			int index = interf.timeLineList.getSelectedIndex();
			if(index == -1)
				return;
			interf.musicList.deleteMusic(index);
			interf.timeLinePanel.updateList();
		} else if(e.getSource() == exports) {
			ImportExport.exportWithDialog(interf.musicList);
		} else if(e.getSource() == imports) {
			MusicList newActionList = ImportExport.importsWithDialog();
			if(newActionList != null)
				interf.musicList = newActionList;
			interf.timeLinePanel.updateList();
		}
	}
}
