<?php

namespace App\Modules\Network\Commands;

use Log;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

// Creatia Core
use App\Models\Asns;

// Module Specifics
use App\Modules\Network\Models\Prefixes;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Ports prefixes from a JSON file that is laid out of the form ASN:{IP}';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $file = json_decode(file_get_contents(storage_path('prefix-import.json')), true);
        $asns = Asns::all()->keyBy('asn');

        

        foreach($file as $asn => $prefixes) {
            foreach($prefixes as $prefix) {
                [$address, $mask] = explode('/', $prefix);

                // Check if it already exists...
                if(Prefixes::where([['address', '=', $address], ['mask', '=', $mask]])->count()) {

                }
                else {
                    Prefixes::insert([[
                        'created_at'        => Carbon::now(),
                        'updated_at'        => Carbon::now(),
                        'deleted_at'        => null,
                        'seen_at'           => Carbon::now(),
                        'address'           => $address,
                        'mask'              => $mask,
                        'still_announced'   => 1,
                        'created_source'    => 'ported',
                        'organisation_id'   => $asns["$asn"]->organisation_id,
                        'asn_id'            => $asns["$asn"]->id,
                    ]]);
                }
            }
        }

        return 0;
    }
}