<?php

function median($array) {
	sort($array);

	return $array[round(count($array) / 2)];
}


$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
	if (! $fileinfo->isDot() && is_dir($fileinfo)) {
		$subDir = new DirectoryIterator($fileinfo);



		echo $fileinfo . "\n";

		$fmp = [];
		$interactive = [];


		foreach ($subDir as $jsonFile) {
			$metrics = processFile($fileinfo . "/" . $jsonFile);

			$fmp[] = $metrics['FMP'];
			$interactive[] = $metrics['Interactive'];
		}

		echo "FMP Median: " . median($fmp) . "\n";
		echo "Interactive Median: " . median($interactive) . "\n";

	}
}


function processFile($json) {
	$fileContent = file_get_contents($json);

	$jsonAsArray = json_decode($fileContent, TRUE);


	return $metrics = [
		'FMP' => $jsonAsArray['audits']['first-meaningful-paint']['numericValue'],
		'Interactive' => $jsonAsArray['audits']['interactive']['numericValue']
	];
}
