#!/usr/bin/env php
<?php

use GuzzleHttp\Client;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\VarExporter\VarExporter;
use function GuzzleHttp\json_decode;
use function GuzzleHttp\Promise\all;

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

$httpClient = new Client(['base_uri' => 'https://chromium-i18n.appspot.com']);
$httpQueue = [];
$responses = [];

$unwrap = function (ResponseInterface $response) {
    return json_decode($response->getBody()->getContents());
};

echo "Fetching country list...\r\n";
$countries = explode('~', json_decode(
    $httpClient->get('/ssl-address/data')->getBody()->getContents()
)->countries);

echo "Fetching country data...\r\n";
foreach ($countries as $i => $country) {
    $httpQueue[] = $httpClient->getAsync("/ssl-address/data/{$country}")->then($unwrap);

    if (($i !== 0 && $i % 10 === 0) || $i + 1 === count($countries)) {
        $responses = array_merge($responses, all($httpQueue)->wait());
        $httpQueue = [];
        usleep(500000);
    }
}

echo "Compiling data...\r\n";
$examples = [];
$patterns = [];

foreach ($responses as $response) {
    if (isset($response->zip, $response->zipex)) {
        $examples[$response->key] = explode(',', $response->zipex)[0];
        $patterns[$response->key] = "/^(?:{$response->zip})$/i";
    } else {
        $patterns[$response->key] = null;
    }
}

echo "Writing files...\r\n";
foreach ([
             __DIR__ . '/../resources/examples.php' => $examples,
             __DIR__ . '/../resources/patterns.php' => $patterns,
         ] as $path => $data) {

    if (!$handle = @fopen($path, 'w')) {
        echo 'Unable to write to file: ' . $path;
        exit(1);
    }

    fwrite($handle, '<?php

/*
|--------------------------------------------------------------------------
| Laravel Postal Codes Validation
|--------------------------------------------------------------------------
|
| This resource file is generated from Google\'s Address Validation
| Metadata API. Please do not edit this file directly, pull requests
| containing changes to this file will not be accepted!
|
| For more information on the API refer to Google\'s public repository:
| https://github.com/google/libaddressinput
|
*/

return ');
    fwrite($handle, stripslashes(VarExporter::export($data)));
    fwrite($handle, ';
');
    fclose($handle);
}

echo "Done.\r\n";
