package addOns;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.ArrayList;
import java.util.DoubleSummaryStatistics;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.function.Supplier;
import java.util.stream.Collectors;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextField;

import api.AddOn;
import classes.Flexibility;
import classes.HolonElement;
import classes.HolonElement.Priority;
import ui.controller.Control;
import ui.controller.FlexManager.FlexState;
import ui.model.DecoratedHolonObject.HolonObjectState;
import ui.model.DecoratedState;
import ui.model.DecoratedSwitch.SwitchState;
import ui.model.VisualRepresentationalState;

public class InformationPanel implements AddOn {
	Control control;
	
	private JPanel content = new JPanel();
	private JScrollPane scrollPane;
	
	
	//Fields
	private int amountSwitch;
	private int amountActiveSwitch;
	private int amountInactiveSwitch;
	private int amountHolonObjects;
		private int amountConsumer;
			private int	amountUnderSupplied;
			private int amountPatiallySupplied;
			private int amountFullySupplied;
			private int amountOversupllied;
		private int amountSupplier;
	private DoubleSummaryStatistics partiallySuppliedStats;
	private DoubleSummaryStatistics overSuppliedStats;
	
	private int amountHolonElements;
		private int amountElementEssential;
		private int amountElementHigh;
		private int amountElementMedium;
		private int amountElementLow;
		private int amountElementActiveEssential;
		private int amountElementActiveHigh;
		private int amountElementActiveMedium;
		private int amountElementActiveLow;
		private int amountElementInactiveEssential;
		private int amountElementInactiveHigh;
		private int amountElementInactiveMedium;
		private int amountElementInactiveLow;
	private int amountActiveHolonElements;
	private int amountInactiveHolonElements;
	private int amountFlexibilities;
	private int amountActiveFlexibilities;
		private int amountEssential;
		private int amountActiveEssential;
		private int amountHigh;
		private int amountActiveHigh;
		private int amountMedium;
		private int amountActiveMedium;
		private int amountLow;
		private int amountActiveLow;

		private int amountConsumingFlexibilities;
		private int amountProducingFlexibilities;
	private int amountPassiv;
		
	private int amountGroupNodes;
	private int amountHolons;
	
	List<IEntry> entryList = new ArrayList<IEntry>();

	private int currentEntryVerticalPosition = 0;





	Random r = new Random();




	
	
	public InformationPanel(){
		content.setLayout(new BorderLayout());
		scrollPane = new JScrollPane(createMiddlePanel(),  JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
	            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		int size = 75;
		scrollPane.setPreferredSize(new Dimension(16*size, 9*size));
		content.add(scrollPane, BorderLayout.CENTER);
		JButton button = new JButton("calculate");
		button.addActionListener(action -> updateEntrys());
		content.add(button, BorderLayout.SOUTH);
	}
	
	public static void main(String[] args)
	{
	      JFrame newFrame = new JFrame("exampleWindow");
	      InformationPanel instance = new InformationPanel();
	      newFrame.setContentPane(instance.getPanel());
	      newFrame.pack();
	      newFrame.setVisible(true);
	      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	
	private JPanel createMiddlePanel() {
		JPanel middle = new JPanel();
		middle.setLayout(new GridBagLayout());
		
		
		

		entryList.add(new Entry(() -> Integer.toString(amountHolonObjects), "HolonObjects", middle));
		entryList.add(new Entry(() -> Integer.toString(amountConsumer) + addPercentage(amountConsumer, amountHolonObjects), "\tConsumer", middle));
		entryList.add(new Entry(() -> Integer.toString(amountUnderSupplied) + addPercentage(amountUnderSupplied, amountConsumer), "\t\tUnderSupplied", middle));
		entryList.add(new Entry(() -> Integer.toString(amountPatiallySupplied) + addPercentage(amountPatiallySupplied, amountConsumer), "\t\tPatiallySupplied", middle));
		entryList.add(new StatEntry(() -> StatToFancyString(partiallySuppliedStats), middle));		
		entryList.add(new Entry(() -> Integer.toString(amountFullySupplied) + addPercentage(amountFullySupplied, amountConsumer), "\t\tFullySupplied", middle));
		entryList.add(new Entry(() -> Integer.toString(amountOversupllied) + addPercentage(amountOversupllied, amountConsumer), "\t\tOversupllied", middle));
		entryList.add(new StatEntry(() -> StatToFancyString(overSuppliedStats), middle));
		entryList.add(new Entry(() -> Integer.toString(amountSupplier) + addPercentage(amountSupplier, amountHolonObjects), "\tSupplier", middle));
		entryList.add(new Entry(() -> Integer.toString(amountPassiv) + addPercentage(amountPassiv, amountHolonObjects), "\tPassiv", middle));
		addSeperator(middle);
		entryList.add(new Entry(() -> Integer.toString(amountSwitch), "Switch (not a HolonObject)", middle));
		entryList.add(new Entry(() -> Integer.toString(amountActiveSwitch) + addPercentage(amountActiveSwitch, amountSwitch), "\t[Active] Switch", middle));
		entryList.add(new Entry(() -> Integer.toString(amountInactiveSwitch) + addPercentage(amountInactiveSwitch, amountSwitch), "\t[Inactive] Switch", middle));
		
		addSeperator(middle);
		entryList.add(new Entry(() -> Integer.toString(amountHolonElements), "HolonElements", middle));
		entryList.add(new Entry(() -> Integer.toString(this.amountElementLow) + addPercentage(amountElementLow, amountHolonElements), "\tLow", middle));
		entryList.add(new Entry(() -> Integer.toString(this.amountElementMedium) + addPercentage(amountElementMedium, amountHolonElements), "\tMedium", middle));
		entryList.add(new Entry(() -> Integer.toString(this.amountElementHigh) + addPercentage(amountElementHigh, amountHolonElements), "\tHigh", middle));
		entryList.add(new Entry(() -> Integer.toString(this.amountElementEssential) + addPercentage(amountElementEssential, amountHolonElements), "\tEssential", middle));
		addSeperator(middle);
		entryList.add(new Entry(() -> Integer.toString(amountActiveHolonElements) + addPercentage(amountActiveHolonElements, amountHolonElements), "[Active] HolonElements", middle));
		entryList.add(new Entry(() -> Integer.toString(this.amountElementActiveLow) + addPercentage(amountElementActiveLow, amountActiveHolonElements), "\tLow", middle));
		entryList.add(new Entry(() -> Integer.toString(this.amountElementActiveMedium) + addPercentage(amountElementActiveMedium, amountActiveHolonElements), "\tMedium", middle));
		entryList.add(new Entry(() -> Integer.toString(this.amountElementActiveHigh) + addPercentage(amountElementActiveHigh, amountActiveHolonElements), "\tHigh", middle));
		entryList.add(new Entry(() -> Integer.toString(this.amountElementActiveEssential) + addPercentage(amountElementActiveEssential, amountActiveHolonElements), "\tEssential", middle));
		addSeperator(middle);
		entryList.add(new Entry(() -> Integer.toString(amountInactiveHolonElements) + addPercentage(amountInactiveHolonElements, amountHolonElements), "[Inactive] HolonElements", middle));
		entryList.add(new Entry(() -> Integer.toString(this.amountElementInactiveLow) + addPercentage(amountElementInactiveLow, amountInactiveHolonElements), "\tLow", middle));
		entryList.add(new Entry(() -> Integer.toString(this.amountElementInactiveMedium) + addPercentage(amountElementInactiveMedium, amountInactiveHolonElements), "\tMedium", middle));
		entryList.add(new Entry(() -> Integer.toString(this.amountElementInactiveHigh) + addPercentage(amountElementInactiveHigh, amountInactiveHolonElements), "\tHigh", middle));
		entryList.add(new Entry(() -> Integer.toString(this.amountElementInactiveEssential) + addPercentage(amountElementInactiveEssential, amountInactiveHolonElements), "\tEssential", middle));
		
		addSeperator(middle);
		entryList.add(new Entry(() -> Integer.toString(amountFlexibilities), "Flexibilities", middle));
		entryList.add(new Entry(() -> Integer.toString(amountConsumingFlexibilities) + addPercentage(amountConsumingFlexibilities, amountFlexibilities), "\tConsumingFlexibilities", middle));
		entryList.add(new Entry(() -> Integer.toString(amountProducingFlexibilities) + addPercentage(amountProducingFlexibilities, amountFlexibilities), "\tProducingFlexibilities", middle));
		addSeperator(middle);
		entryList.add(new Entry(() -> Integer.toString(amountFlexibilities), "Flexibilities", middle));
		entryList.add(new Entry(() -> Integer.toString(amountLow) + addPercentage(amountLow, amountFlexibilities), "\tLow", middle));
		entryList.add(new Entry(() -> Integer.toString(amountMedium) + addPercentage(amountMedium, amountFlexibilities), "\tMedium", middle));
		entryList.add(new Entry(() -> Integer.toString(amountHigh) + addPercentage(amountHigh, amountFlexibilities), "\tHigh", middle));
		entryList.add(new Entry(() -> Integer.toString(amountEssential) + addPercentage(amountEssential, amountFlexibilities), "\tEssential", middle));
		addSeperator(middle);
		entryList.add(new Entry(() -> Integer.toString(amountActiveFlexibilities), "ActiveFlexibilities", middle));
		entryList.add(new Entry(() -> Integer.toString(amountActiveLow) + addPercentage(amountActiveLow, amountActiveFlexibilities), "\tLow", middle));
		entryList.add(new Entry(() -> Integer.toString(amountActiveMedium) + addPercentage(amountActiveMedium, amountActiveFlexibilities), "\tMedium", middle));
		entryList.add(new Entry(() -> Integer.toString(amountActiveHigh) + addPercentage(amountActiveHigh, amountActiveFlexibilities), "\tHigh", middle));
		entryList.add(new Entry(() -> Integer.toString(amountActiveEssential) + addPercentage(amountActiveEssential, amountActiveFlexibilities), "\tEssential", middle));
		addSeperator(middle);
		entryList.add(new Entry(() -> Integer.toString(amountGroupNodes), "GroupNodes", middle));
		entryList.add(new Entry(() -> Integer.toString(amountHolons), "Holons", middle));
		
		return middle;
	}

	String addPercentage(int amountActual, int amountMaximum) {
		return (amountMaximum > 0) ? "                " + String.format (Locale.US, "%.2f", ((float) amountActual) / ((float) amountMaximum) * 100) + "%" : "";
	}
	
	
	
	private void addSeperator(JPanel middle) {
		GridBagConstraints c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridwidth = 2;
		c.weighty = 0.5;
		c.weightx = 0.5;
		c.gridx = 0;
		c.gridy = this.currentEntryVerticalPosition++;
		middle.add(new JSeparator(JSeparator.HORIZONTAL), c);
	}

	private GridBagConstraints createGbConstrain(int x, int y) {
		GridBagConstraints c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
		c.insets = new Insets(3,6, 3, 6);  
		c.weighty = 0.5;
		c.weightx = 0.5;
		c.gridx = x;
		c.gridy = y;
		return c;
	}
	
	
	void updateEntrys() {
		calculateValues();
		entryList.forEach(entry -> entry.update());
		//printInfos();
	}
	
	
	void calculateValues(){
		DecoratedState dState = control.getSimManager().getActualDecorState();
		amountConsumer = dState.getNetworkList().stream().map(net -> net.getAmountOfConsumer()).reduce(0, Integer::sum);
		this.amountSwitch = dState.getDecoratedSwitches().size();
		amountActiveSwitch = (int)dState.getDecoratedSwitches().stream().filter(dswitch -> (dswitch.getState() == SwitchState.Closed)).count();
		amountInactiveSwitch = amountSwitch - amountActiveSwitch;
		this.amountUnderSupplied = dState.getNetworkList().stream().map(net -> net.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED)).reduce(0, Integer::sum);
		this.amountPatiallySupplied = dState.getNetworkList().stream().map(net -> net.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED)).reduce(0, Integer::sum);
		
		this.amountFullySupplied = dState.getNetworkList().stream().map(net -> net.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED)).reduce(0, Integer::sum);
		this.amountOversupllied = dState.getNetworkList().stream().map(net -> net.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED)).reduce(0, Integer::sum);
		amountSupplier = dState.getNetworkList().stream().map(net -> net.getAmountOfSupplier()).reduce(0, Integer::sum);
		amountPassiv = dState.getNetworkList().stream().map(net -> net.getAmountOfPassiv()).reduce(0, Integer::sum);
		
		this.amountHolonObjects = amountConsumer + amountSupplier + amountPassiv;
		
		partiallySuppliedStats = dState.getNetworkList().stream().flatMap(net -> {
			return net.getConsumerList().stream().filter(con -> con.getState() == HolonObjectState.PARTIALLY_SUPPLIED);
		}).mapToDouble(con -> con.getSupplyBarPercentage()).summaryStatistics();
		
		overSuppliedStats = dState.getNetworkList().stream().flatMap(net -> {
			return net.getConsumerList().stream().filter(con -> con.getState() == HolonObjectState.OVER_SUPPLIED);
		}).mapToDouble(con -> con.getSupplyBarPercentage()).summaryStatistics();
		
		List<Flexibility> flexList = control.getSimManager().getActualFlexManager().getAllFlexWrapper().stream().filter(flexwrapper -> flexwrapper.getFlex().offered).map(flex -> flex.getFlex()).collect(Collectors.toList());
		amountEssential = (int)flexList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Essential).count();
		amountHigh = (int)flexList.stream().filter(flex -> flex.getElement().getPriority() == Priority.High).count();
		amountMedium = (int)flexList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Medium).count();
		amountLow = (int)flexList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Low).count();
		this.amountFlexibilities = amountEssential + amountHigh + amountMedium + amountLow;
		
		
		List<Flexibility> flexActiveList = control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE).stream().map(flex -> flex.getFlex()).collect(Collectors.toList());
		amountActiveEssential = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Essential).count();
		amountActiveHigh = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.High).count();
		amountActiveMedium = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Medium).count();
		amountActiveLow = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Low).count();
		this.amountActiveFlexibilities = amountActiveEssential + amountActiveHigh + amountActiveMedium + amountActiveLow;
		VisualRepresentationalState visualState =control.getSimManager().getActualVisualRepresentationalState();
		amountGroupNodes = visualState.getAmountfOfGroupNodes();
		
		
		amountHolons = dState.getNetworkList().size();
		List<HolonElement> listHolonElements = control.getModel().getAllHolonElemnts();
		this.amountHolonElements = listHolonElements.size();
		List<HolonElement> listAcitveHolonElemnts = listHolonElements.stream().filter(ele -> ele.isActive()).collect(Collectors.toList());
		this.amountActiveHolonElements = listAcitveHolonElemnts.size();
		this.amountInactiveHolonElements = amountHolonElements - amountActiveHolonElements;
		this.amountElementLow = (int) listHolonElements.stream().filter(ele -> ele.getPriority() == Priority.Low).count();
		this.amountElementMedium= (int) listHolonElements.stream().filter(ele -> ele.getPriority() == Priority.Medium).count();
		this.amountElementHigh = (int) listHolonElements.stream().filter(ele -> ele.getPriority() == Priority.High).count();
		this.amountElementEssential = (int) listHolonElements.stream().filter(ele -> ele.getPriority() == Priority.Essential).count();
		this.amountElementActiveLow = (int) listAcitveHolonElemnts.stream().filter(ele -> ele.getPriority() == Priority.Low).count();
		this.amountElementActiveMedium= (int) listAcitveHolonElemnts.stream().filter(ele -> ele.getPriority() == Priority.Medium).count();
		this.amountElementActiveHigh = (int) listAcitveHolonElemnts.stream().filter(ele -> ele.getPriority() == Priority.High).count();
		this.amountElementActiveEssential = (int) listAcitveHolonElemnts.stream().filter(ele -> ele.getPriority() == Priority.Essential).count();
		this.amountElementInactiveLow = amountElementLow - amountElementActiveLow;
		this.amountElementInactiveMedium= amountElementMedium - amountElementActiveMedium;
		this.amountElementInactiveHigh = amountElementHigh - amountElementActiveHigh;
		this.amountElementInactiveEssential = amountElementEssential - amountElementActiveEssential;
		
		
		
		int cost = 0;
		int consumingFlex = 0;
		float consumingFlexEnergy = 0.0f;
		int producingFlex = 0;
		float producingFlexEnergy = 0.0f;
		int maxCooldown = 0;
		for(Flexibility flex :flexList) {
			cost += flex.cost;
			float energy = flex.bringtmir();
			if(energy < 0) {
				consumingFlex++;
				consumingFlexEnergy += -energy;
			}else {
				producingFlex++;
				producingFlexEnergy += energy;
			}
		}
		this.amountConsumingFlexibilities = consumingFlex;
		this.amountProducingFlexibilities = producingFlex;
		
	}
	

	
	

	
	@Override
	public JPanel getPanel() {
		return content;
	}

	@Override
	public void setController(Control control) {
		this.control = control;
		if(control != null)  updateEntrys();
	}
	
	private class Entry implements IEntry{
		public Entry( Supplier<String> getter, String label, JPanel panel) {
			this.getter = getter;
			//RegisterToPanel
			label = label.replaceAll("\t", "                   ");
			JLabel jlabel = new JLabel(label);
			panel.add(jlabel, createGbConstrain(0, currentEntryVerticalPosition));
			tf = new JTextField(getter.get());
			tf.setEditable(false);
			panel.add(tf, createGbConstrain(1, currentEntryVerticalPosition));
			currentEntryVerticalPosition++;
		}
		
		private JTextField tf; //the Textfield to update
		private Supplier<String> getter; //Getter for the field
		public void update() {
			tf.setText(getter.get());
		}
		
		
		
	}
	private String StatToFancyString (DoubleSummaryStatistics stats) {
		return "Min:" + stats.getMin() + " Max:" + stats.getMax() + " Average:" + stats.getAverage();
	}
	public  class StatEntry implements IEntry 
	{
		JLabel textLabel = new JLabel("Nothing");
		private Supplier<String> updateFunction = null;
		public StatEntry( Supplier<String> updateText, JPanel panel){
			updateFunction = updateText;
			panel.add(textLabel, createGbConstrain(1, currentEntryVerticalPosition));
			currentEntryVerticalPosition++;
		}
		@Override
		public void update() {
			textLabel.setText(updateFunction.get());
		}
	}
	
	
	private interface IEntry{
		public void update();
	}
}
