package clustering.kmeans;

import java.util.Vector;

public class JCA {
	Vector<double[]> clusterCentroids = new Vector();
	Vector<int[]> arrayClusters = new Vector();
	Vector errors = new Vector();
	static final int MINUTES_OF_A_DAY = 24*60;
	private Cluster[] clusters;
	private int miter;
	private Vector mDataPoints = new Vector();
	private double mSWCSS;

	public JCA(int k, int iter, Vector<DataPoint> dataPoints) {
		clusters = new Cluster[k];
		for (int i = 0; i < k; i++) {
			clusters[i] = new Cluster("Cluster" + i);
		}
		this.miter = iter;
		this.mDataPoints = dataPoints;
	}

	// Total Sum Square of all clusters' sum squares to evaluate the global sum
	// of squares
	private void calcSWCSS() {
		double temp = 0;
		for (int i = 0; i < clusters.length; i++) {
			temp = temp + clusters[i].getSumSqr();
		}
		mSWCSS = temp;
	}

	public void startAnalysis() {
		// set Starting centroid positions - Start of Step 1
		setInitialCentroids();
		int n = 0;
		// assign DataPoint to clusters equally one to one
		loop1: while (true) {
			for (int l = 0; l < clusters.length; l++) {
				clusters[l].addDataPoint((DataPoint) mDataPoints.elementAt(n));
				n++;
				if (n >= mDataPoints.size())
					break loop1;
			}
		}

		System.out.println("Default registering data to clusters");

		for (int k = 0; k < clusters.length; k++) {
			arrayClusters.add(saveCurrentClusterInfo(clusters, k));
			clusterCentroids.add(clusters[k].getCentroid().getBatteryLevel().clone());
		}
		
		
		for (int l = 0; l < clusters.length; l++) {
			System.out.println("Cluster " + l + ": ");
			System.out.println("Has Centroid: ");
			System.out.println(clusters[l].getCentroid().print());
			System.out.print("Has sensors: ");
			for (int i = 0; i < arrayClusters.elementAt(l).length; i++) {
				System.out.print(arrayClusters.elementAt(l)[i] + ", ");
			}
			System.out.println();
		}
		// calculate E for all the clusters
		System.out.println();
		calcSWCSS();
		//Saving SSE of this step
		errors.add(this.getSWCSS());
		System.out.println("Error: " + this.mSWCSS + "\n");

		// recalculate Cluster centroids - Start of Step 2
		for (int l = 0; l < clusters.length; l++) {
			clusters[l].getCentroid().calcCentroid();
		}
		for (int k = 0; k < clusters.length; k++) {
			arrayClusters.add(saveCurrentClusterInfo(clusters, k));
			clusterCentroids.add(clusters[k].getCentroid().getBatteryLevel().clone());
		}
	
		for (int l = 0; l < clusters.length; l++) {
			System.out.println("Cluster " + l + ": ");
			System.out.println("Has Centroid: ");
			System.out.println(clusters[l].getCentroid().print());
			System.out.print("Has sensors: ");
			for (int i = 0; i < clusters[l].getNumDataPoints(); i++) {
				System.out.print(clusters[l].getDataPoint(i).getSensorId()
						+ ", ");
			}
			System.out.println();
		}

		// recalculate E for all the clusters
		// System.out.println();
		calcSWCSS();
		//Saving SSE of this step
		errors.add(this.getSWCSS());
		System.out.println("Error: " + this.mSWCSS);
		System.out.println();
		// Start the new loop for calculating
		for (int i = 0; i < miter; i++) {
			// enter the loop for cluster 1
			for (int j = 0; j < clusters.length; j++) {
				for (int k = 0; k < clusters[j].getNumDataPoints(); k++) {

					// pick the first element of the first cluster
					// get the current Euclidean distance
					double tempEuDt = clusters[j].getDataPoint(k)
							.getCurrentEuDt();
					Cluster tempCluster = null;
					boolean matchFoundFlag = false;

					// call testEuclidean distance for all clusters
					for (int l = 0; l < clusters.length; l++) {
						// if testEuclidean < currentEuclidean then
						if (tempEuDt > clusters[j].getDataPoint(k)
								.testEuclideanDistance(
										clusters[l].getCentroid())) {
							tempEuDt = clusters[j].getDataPoint(k)
									.testEuclideanDistance(
											clusters[l].getCentroid());
							tempCluster = clusters[l];
							matchFoundFlag = true;
						}
						// if statement - Check whether the Last EuDt is >
						// Present EuDt
					}
					// for variable 'l' - Looping between different Clusters for
					// matching a Data
					// Point.
					// add DataPoint to the cluster and calcSWCSS

					if (matchFoundFlag) {
						tempCluster.addDataPoint(clusters[j].getDataPoint(k));
						clusters[j]
								.removeDataPoint(clusters[j].getDataPoint(k));
						for (int m = 0; m < clusters.length; m++) {
							clusters[m].getCentroid().calcCentroid();
						}
						// for variable 'm' - Recalculating centroids for all
						// Clusters
						for (int m = 0; m < clusters.length; m++) {
							arrayClusters.add(saveCurrentClusterInfo(clusters,
									m));
							clusterCentroids.add(clusters[m].getCentroid()
									.getBatteryLevel().clone());
						}
						

						for (int l = 0; l < clusters.length; l++) {
							System.out.println("Cluster " + l + ": ");
							System.out.println("Has Centroid: ");
							System.out.println(clusters[l].getCentroid()
									.print());
							System.out.print("Has sensors: ");
							for (int m = 0; m < clusters[l].getNumDataPoints(); m++) {
								System.out.print(clusters[l].getDataPoint(m)
										.getSensorId()
										+ ", ");
							}
							System.out.println();
						}
						System.out.println();
						calcSWCSS();
						//Saving SSE of this step
						errors.add(this.getSWCSS());
						System.out.println("Error: " + this.mSWCSS + "\n");
					}

					// if statement - A Data Point is eligible for transfer
					// between Clusters.
				}
				// for variable 'k' - Looping through all Data Points of the
				// current Cluster.
			}// for variable 'j' - Looping through all the Clusters.
		}// for variable 'i' - Number of iterations.
	}

	public Vector[] getClusterOutput() {
		Vector v[] = new Vector[clusters.length];
		for (int i = 0; i < clusters.length; i++) {
			v[i] = clusters[i].getDataPoints();
		}
		return v;
	}

	public Centroid[] getCentroids() {
		Centroid c[] = new Centroid[clusters.length];
		for (int i = 0; i < clusters.length; i++) {
			c[i] = clusters[i].getCentroid();
		}
		return c;
	}

	private void setInitialCentroids() {
		// kn = (round((max-min)/k)*n)+min where n is from 0 to (k-1).

		for (int n = 1; n <= clusters.length; n++) {
			double[] tempBatteryLevel = new double[MINUTES_OF_A_DAY];
			for (int m = 0; m < MINUTES_OF_A_DAY; m++) {
				tempBatteryLevel[m] = (((getMaxBatteryLevel(m) - getMinBatteryLevel(m)) / (clusters.length + 1)) * n)
						+ getMinBatteryLevel(m);
			}

			Centroid c1 = new Centroid(tempBatteryLevel);
			System.out.println("Centroid " + (n - 1) + c1.print());
			clusters[n - 1].setCentroid(c1);
			c1.setCluster(clusters[n - 1]);
		}
		System.out.println("---------------------------------------");

	}

	private double getMaxBatteryLevel(int m) {
		double temp;
		temp = ((DataPoint) mDataPoints.elementAt(0)).getBatteryLevel()[m];
		for (int i = 0; i < mDataPoints.size(); i++) {
			DataPoint dp = (DataPoint) mDataPoints.elementAt(i);
			temp = (dp.getBatteryLevel()[m] > temp) ? dp.getBatteryLevel()[m]
					: temp;
		}
		return temp;
	}

	private double getMinBatteryLevel(int m) {
		double temp = 0;
		temp = ((DataPoint) mDataPoints.elementAt(0)).getBatteryLevel()[m];
		for (int i = 0; i < mDataPoints.size(); i++) {
			DataPoint dp = (DataPoint) mDataPoints.elementAt(i);
			temp = (dp.getBatteryLevel()[m] < temp) ? dp.getBatteryLevel()[m]
					: temp;
		}
		return temp;
	}

	public int getKValue() {
		return clusters.length;
	}

	public int getIterations() {
		return miter;
	}

	public int getTotalDataPoints() {
		return mDataPoints.size();
	}

	public double getSWCSS() {
		return mSWCSS;
	}

	public Cluster getCluster(int pos) {
		return clusters[pos];
	}

	// Function to get sensors at each step:
	public int[] saveCurrentClusterInfo(Cluster[] clusters, int clusterID) {
		int ndp = clusters[clusterID].getNumDataPoints();
		int[] temp = new int[ndp];
		for (int i = 0; i < ndp; i++) {
			temp[i] = clusters[clusterID].getDataPoint(i).getSensorId();
		}
		return temp;
	}

	// takes loopId and clusterID returns list of sensorId inside it.
	public int[] decode(int loopId, int clusterId) {
		int[] temp;
		clusterId = clusterId + loopId * this.getKValue();
		temp = this.arrayClusters.elementAt(clusterId);
		return temp;
	}

	public double[] getCentroidData(int loopId, int clusterId) {
		clusterId = clusterId + loopId * this.getKValue();
		double[] temp = new double[this.clusterCentroids.elementAt(clusterId).length];
		for(int i=0; i< this.clusterCentroids.elementAt(clusterId).length; i++){
			temp[i] = this.clusterCentroids.elementAt(clusterId)[i];
		}
		
		return temp;
	}

	public int getLoopsNumber() {
		int temp = this.arrayClusters.size() / this.getKValue();
		return temp;
	}
	
	public double getErrors(int loopId){
		return  Double.parseDouble(this.errors.elementAt(loopId).toString());
	}
}