package kinesisFHM.utilities;

import com.amazonaws.auth.profile.ProfilesConfigFile;
import com.amazonaws.services.cloudwatch.AmazonCloudWatchClient;
import com.amazonaws.services.cloudwatch.model.Datapoint;
import com.amazonaws.services.cloudwatch.model.Dimension;
import com.amazonaws.services.cloudwatch.model.GetMetricStatisticsRequest;
import com.amazonaws.services.cloudwatch.model.GetMetricStatisticsResult;
import com.amazonaws.services.cloudwatch.model.StandardUnit;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class GetCloudWatchMetrics {

	
	private static void appendMetricStatistics(AmazonCloudWatchClient amazonCloudWatchClient, File outputFile, String metricName, String streamName, int minutes) {
		try {
			SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
//			dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
			SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
			Date end = dateFormatLocal.parse( dateFormatGmt.format(new Date()) );

			Calendar cal = Calendar.getInstance();
			cal.setTime(end);
			cal.add(Calendar.MINUTE, -minutes);
			Date start = cal.getTime();
			
			GetMetricStatisticsResult result = amazonCloudWatchClient.getMetricStatistics(new GetMetricStatisticsRequest()
														.withNamespace("kinesisFHM")
														.withStatistics("Sum")
														.withUnit(StandardUnit.Count)
														.withMetricName(metricName)
														.withPeriod(60)
														.withDimensions(new Dimension().withName("StreamName").withValue(streamName))
														.withEndTime(end)
														.withStartTime(start)
														);
			PrintWriter pw = new PrintWriter(new FileOutputStream(outputFile, true));
			for (Datapoint dp : result.getDatapoints()) {
				pw.println(metricName + ", " + streamName + ", " + dateFormatLocal.format(dp.getTimestamp()) + ", " + dp.getSum()/60 );
			}
			pw.close();
			System.err.println("Received " + result.getDatapoints().size() + " datapoints for kinesisFHM " + metricName + " metric for " + streamName + " for the last " + minutes + " minutes.");
						
		} catch (Exception e) { e.printStackTrace(); }
	}
	
	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		if (args.length < 4) {
			System.err.println("Usage: GetCloudWatchMetrics credentialFileName awsProfileName minutes outputFileName");
			System.exit(-1);
		}
		
		String credentialFileName = args[0];
		String awsProfileName = args[1];
		Integer minutes = Integer.parseInt(args[2]);
		File outputFile = new File(args[3]);

		AmazonCloudWatchClient amazonCloudWatchClient = new AmazonCloudWatchClient(new ProfilesConfigFile(credentialFileName).getCredentials(awsProfileName));

		Files.deleteIfExists(outputFile.toPath());
		for (String i : new String[]{"PutRecords", "ReadRecords"} ) {
			for (String j : new String[]{"EventStream", "RelationStream", "UpdateStream", "GraphUpdateStream", "TraceStream"} ) {
				appendMetricStatistics(amazonCloudWatchClient, outputFile, i, j, minutes);
			}
		}
	}

}
