package addOns;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.Hashtable;

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

import api.AddOn;
import classes.HolonSwitch;
import ui.controller.Control;

public class RandomSwitch implements AddOn {
	private double  randomChance = 0.5;
	private Control  control;
	
	private JPanel content = new JPanel();
//	To Test the Layout Faster   
//	public static void main(String[] args)
//    {
//        JFrame newFrame = new JFrame("exampleWindow");
//        RandomSwitch instance = new RandomSwitch();
//        newFrame.setContentPane(instance.getAlgorithmPanel());
//        newFrame.pack();
//        newFrame.setVisible(true);
//	      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//    }
	
	public RandomSwitch(){
		content.setLayout(new BorderLayout());
		content.add(createParameterPanel(), BorderLayout.CENTER);
		JButton buttonRun = new JButton("Run");
		buttonRun.addActionListener(actionEvent -> run());
		content.add(buttonRun, BorderLayout.PAGE_END);
		content.setPreferredSize(new Dimension(300,300));
	}
	private JPanel createParameterPanel() {
		JPanel parameterPanel = new JPanel();
		parameterPanel.setLayout(new BoxLayout(parameterPanel, BoxLayout.PAGE_AXIS));
		parameterPanel.add(createFlipChanceSlider());
		return parameterPanel;
	}
	private JSlider createFlipChanceSlider() {
		JSlider flipChance =new JSlider(JSlider.HORIZONTAL,0, 100, 50);
		flipChance.setBorder(BorderFactory.createTitledBorder("FlipChance"));
		flipChance.setMajorTickSpacing(50);
		flipChance.setMinorTickSpacing(5);
		flipChance.setPaintTicks(true);
		Hashtable<Integer, JLabel> labelTable = new Hashtable<Integer, JLabel>();
		labelTable.put( Integer.valueOf(0), new JLabel("0.0") );
		labelTable.put( Integer.valueOf(50), new JLabel("0.5") );
		labelTable.put( Integer.valueOf(100), new JLabel("1.0") );
		flipChance.addChangeListener(actionEvent ->randomChance =(double)flipChance.getValue()/100.0);
		flipChance.setLabelTable( labelTable );
		flipChance.setPaintLabels(true);
		return flipChance;
	}
	private void run() {
		for (HolonSwitch s : control.getModel().getAllSwitches()) {
			// Set to Manual Mode
			s.setManualMode(true);
			// Generate a random number between 0 and 1
			double randomDouble = Math.random();
			if (randomDouble < randomChance) {
				s.setManualState(!s.getManualState());
			} 
		}
		control.calculateStateAndVisualForCurrentTimeStep();
		control.updateCanvas();
	}
	@Override
	public JPanel getPanel() {
		return content;
	}
	@Override
	public void setController(Control control) {
		this.control = control;
		
	}

}
