<?php

require __DIR__ . '/../vendor/autoload.php';

$jsonfile = __DIR__ . '/../tests/user_agents.dist.json';

$uas = json_decode(
	file_get_contents($jsonfile),
	true
);

$classData = [];

$platforms = [];

foreach( $uas as $key => $val ) {

	$classes = isset($val['class']) ? $val['class'] : [ 'Browsers' ];

	$kex = strtoupper($val['browser']);
	$kex = preg_replace('/\W+/', '_', $kex);
	foreach( $classes as $class ) {
		$classData[$class][$kex][$val['browser']] =
			isset($classData[$class][$kex][$val['browser']]) ?
				$classData[$class][$kex][$val['browser']] + 1 : 1;
	}

	$kex = strtoupper((string)$val['platform']);
	if( $kex !== '' ) {
		$kex = preg_replace('/\W+/', '_', $kex);

		if( !isset($platforms[$kex][$val['platform']]) ) {
			$platforms[$kex][$val['platform']] = 0;
		}

		$platforms[$kex][$val['platform']]++;
	}


}

$file   = basename(__FILE__);
$header = <<<EOT
<?php

// DO NOT EDIT THIS FILE - IT IS GENERATED BY {$file}


EOT;

foreach( $classData as $className => $browsers ) {
	ksort($browsers);

	$browserBody = "{$header}namespace donatj\UserAgent;\n\ninterface {$className} {\n\n";
	$maxKey      = max(array_map('strlen', array_keys($browsers)));

	foreach( $browsers as $const => $val ) {
		$browserBody .= sprintf("\tconst %-{$maxKey}s = %s;\n", $const, var_export(key($val), true));
	}
	$browserBody .= "\n}\n\n";

	file_put_contents(__DIR__ . '/../src/UserAgent/'.$className.'.php', $browserBody);
}

foreach( $platforms as $platform ) {
	if( count($platform) !== 1 ) {
		echo "bad platform count\n";
		die(2);
	}
}

$platformBody = "{$header}namespace donatj\UserAgent;\n\ninterface Platforms {\n\n";
$maxKey       = max(array_map('strlen', array_keys($platforms)));
foreach( $platforms as $const => $val ) {
	$platformBody .= sprintf("\tconst %-{$maxKey}s = %s;\n", $const, var_export(key($val), true));
}
$platformBody .= "\n}\n\n";

file_put_contents(__DIR__ . '/../src/UserAgent/Platforms.php', $platformBody);
