<?php

namespace App\Modules\Network\Commands;

use App\Modules\Network\Models\GeoIp\PrefixGeoIp;
use App\Helpers\Utility\WhoIs;

class GeoIpSync extends \App\Console\Commands\BaseCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'geoip:sync';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Checks who-is status for each prefix.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        PrefixGeoIp::leftJoin('prefixes', 'prefixes.id', '=', 'prefix_id')->select('address', 'mask', 'prefix_geo_ip.id', 'country')
            ->whereNotNull('country')
            ->chunk(env('CHUNK_SIZE'), function($x) {
                $to_null = [];
                $to_no_entry = [];
                $to_no_country = [];
                $to_not_aligned = [];

                foreach($x as $y) {
                    $who_is_raw = WhoIs::location_lookup("$y->address/$y->mask");

                    $who_is = ($who_is_raw == 'NO_ENTRY' || $who_is_raw == 'NO_COUNTRY') ? $who_is_raw : (array_search($y->country, $who_is_raw) ? null : 'NOT_ALIGNED'); 

                    switch($who_is) {
                        case 'NO_ENTRY':
                            $to_no_entry[] = $y->id;
                            break;
                        case 'NO_COUNTRY':
                            $to_no_country[] = $y->id;
                            break;
                        case 'NOT_ALIGNED':
                            $to_not_aligned[] = $y->id;
                            break;
                        default:
                            $to_null[] = $y->id;
                    }
                }

                PrefixGeoIp::whereIn('id', $to_null)->update([ 'whois_error' => null ]);
                PrefixGeoIp::whereIn('id', $to_no_entry)->update([ 'whois_error' => 'NO_ENTRY' ]);
                PrefixGeoIp::whereIn('id', $to_no_country)->update([ 'whois_error' => 'NO_COUNTRY' ]);
                PrefixGeoIp::whereIn('id', $to_not_aligned)->update([ 'whois_error' => 'NOT_ALIGNED' ]);
        });

        
        return 0;
    }
}