<?php

namespace App\Modules\Network\Commands;

use Log;

use Illuminate\Support\Facades\DB;

use App\Modules\Network\Models\Prefixes;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sets up geolocation objects.';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        try {
            Prefixes::leftJoin('prefix_geo_ip', 'prefix_id', '=', 'prefixes.id')->select('prefixes.id as relevant_id', 'prefixes.organisation_id')->whereNull('prefix_id')->chunk(env('CHUNK_SIZE'), function($prefix_chunk) {
                $to_insert = [];

                foreach($prefix_chunk as $prefix) {
                    $to_insert[] = [
                        'prefix_id'         => $prefix->relevant_id,
                        'country'           => null,
                        'region'            => null,
                        'city'              => null,
                        'organisation_id'   => $prefix->organisation_id,
                        'whois_error'       => null
                    ];
                }

                DB::table('prefix_geo_ip')->insert($to_insert);
            });
        }
        catch(Exception $ex) {}

        return 0;
    }
}