package exampleAlgorithms;

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.Algorithm;
import classes.HolonSwitch;
import ui.controller.Control;

public class RandomSwitch implements Algorithm {
	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);
//    }
	
	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( new Integer( 0 ), new JLabel("0.0") );
		labelTable.put( new Integer( 50 ), new JLabel("0.5") );
		labelTable.put( new Integer( 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().getSwitches()) {
			// 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.getActiveManual());
			} 
		}
		control.calculateStateForCurrentTimeStep();
		control.updateCanvas();
	}
	@Override
	public JPanel getAlgorithmPanel() {
		return content;
	}
	@Override
	public void setController(Control control) {
		this.control = control;
		
	}

}
