package gui.simulator;

import agenda.Agenda;
import agenda.Stage;
import gui.simulator.facilities.SimulatorStage;

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

/**
 * Created by gjoosen on 26/03/15.
 */
public class StageDialog extends JDialog {

    private Agenda agenda;
    private DrawEngine drawEngine;
    private JComboBox<Stage> comboBox;

    public StageDialog(DrawEngine drawEngine, Agenda agenda){
        this.drawEngine = drawEngine;
        this.agenda = agenda;
        super.setContentPane(this.panel());
        super.pack();
        super.setVisible(true);
    }

    private JPanel panel(){
        JPanel panel = new JPanel();
        //TODO dialog
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        if(this.drawEngine instanceof SimulatorStage){
            panel.add(new JLabel("Stage: "));
            this.comboBox = this.comboBox();
            panel.add(this.comboBox);
            panel.add(this.buttons());
        }
        return panel;
    }

    private JPanel buttons(){
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));

        JButton save = new JButton("save");
        save.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                SimulatorStage stage = (SimulatorStage) drawEngine;
                //if stage isn't set
                if(stage.getStage() == null){
                    stage.setStage((Stage) comboBox.getSelectedItem());
                    stage.getStage().setInUse(true);
                }else{
                    stage.getStage().setInUse(false);
                    stage.setStage((Stage) comboBox.getSelectedItem());
                    stage.getStage().setInUse(true);
                }
                dispose();
            }
        });
        panel.add(save);
        return panel;
    }

    private JComboBox<Stage> comboBox(){

        DefaultComboBoxModel<Stage> defaultComboBoxModel = new DefaultComboBoxModel<>();

        for(Stage stage: this.agenda.getStages()){
            if(!stage.inUse()){
                defaultComboBoxModel.addElement(stage);
            }
        }
        JComboBox<Stage> stages = new JComboBox<>(defaultComboBoxModel);
        return stages;
    }
}
