<?php

namespace App\Console\Commands\Network;

use App\Console\Commands\BaseCommand;
use Illuminate\Support\Facades\Http;

class GeoIpList extends BaseCommand
{

    protected $signature = 'geoip:list';

    protected $description = 'Sets up geolocation objects.';

    protected $notEnterprise = true;

    public function handle()
    {
        /* Generating file of the form:
            "ISO3166-1 Code":{
                "name":"ISO3166-1 NME",
                "divisions":{
                    "ISO3166-2 Code":{
                        "name":"ISO3166-2 nAME",
                        "cities":[
                            "Using UN LOCODE list"
                        ]
                    }
                }
            }
         */
        try {

            // Pull in ISO3166-1
            $code_countries = Http::retry(3, 100)
                ->get('https://raw.githubusercontent.com/pycountry/pycountry/main/src/pycountry/databases/iso3166-1.json')
                ->json()['3166-1'];

            // Pull in ISO3166-2
            $code_divisions = Http::retry(3, 100)
                ->get('https://raw.githubusercontent.com/pycountry/pycountry/main/src/pycountry/databases/iso3166-2.json')
                ->json()['3166-2'];

            // Pull in cities
            $city_lookup = [];

            foreach(['unlocode1', 'unlocode2', 'unlocode3'] as $x) {
                $locodes = file_get_contents(storage_path("$x.csv"));

                foreach(explode("\n", $locodes) as $line) {
                    $values = explode(',', str_replace('"', '', $line));

                    if(count($values) >= 5 && $values[5] != '') {
                        if(isset($city_lookup[$values[1]][$values[5]])) {
                            $city_lookup[$values[1]][$values[5]][] = mb_convert_encoding($values[3], "UTF-8", "HTML-ENTITIES");
                        }
                        else {
                            $city_lookup[$values[1]][$values[5]] = [ mb_convert_encoding($values[3], "UTF-8", "HTML-ENTITIES") ];
                        }
                    }
                }
            }

            $output_list = [];

            // Build up countries
            foreach($code_countries as $x) {
                $output_list[$x['alpha_2']] = [
                    'name'      => $x['name'],
                    'divisions' => []
                ];
            }
            
            // Build up divisions
            foreach($code_divisions as $x) {
                [$country, $division] = explode('-', $x['code']);

                $output_list[$country]['divisions']["$country-$division"] = [
                    'name'      => $x['name'],
                    'cities'    => isset($city_lookup[$country][$division]) ? $city_lookup[$country][$division] : [] 
                ];   
            }

            file_put_contents(app_path('Models/GeoIp/RegionCodes.json'), json_encode($output_list, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));

        }
        catch(\Throwable $e) {
            \Log::debug($e);
        }

        return 0;
    }
}