<?php

namespace App\Console\Commands\Broadcast;

use App\Console\Commands\BaseCommand;
use Carbon\Carbon;
use App\Events\SimplePrivateEvent;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Process\Process;

class BroadcastInlineRIB extends BaseCommand
{

    protected $signature = 'broadcast:inline-rib';

    protected $description = 'Broadcasts goliath traffic information.';

    protected $notEnterprise = true;

    public function handle()
    {

        $process = new Process(['/usr/bin/gobgp/gobgp', '--port=50051', '-j',  'global', 'rib']);

        $process->run();

        $rib = [];

        $lookup_large = [
            '7578:666:661' => 'L1',
            '7578:666:662' => 'L2',
            '7578:666:663' => 'L3',
            '7578:666:664' => 'Mercury',
        ];

        $lookup_small = json_decode(file_get_contents(app_path('Models/CommunityLocationLookup.json')), true);

        if($process->isSuccessful()) {

            foreach(json_decode($process->getOutput(), true) as $prefix => $info) {
                $small = [];
                $large = [];
                $tags = [];

                foreach($info[0]['attrs'] as $attr) {

                    switch($attr['type']) {
                        case 8:
                            foreach($attr['communities'] as $x) {
                                $comm = ($x >> 16) . ':' . ($x & 0xFFFF);
                                $small[] = $comm;

                                if(isset($lookup_small[$comm])) {
                                    $tags[] = $lookup_small[$comm];
                                }
                            }
                            break;
                        case 32:
                            foreach($attr['value'] as $x) {
                                $comm = $x['ASN'] . ':' . $x['LocalData1'] . ':' . $x['LocalData2'];
                                $large[] = $comm;

                                if(isset($lookup_large[$comm])) {
                                    $tags[] = $lookup_large[$comm];
                                }
                            }
                            break;
                    }
                }

                $rib[] = [ 'prefix' => $prefix, 'since' => Carbon::parse($info[0]['age'])->format('Y-m-d H:i:s'), 'small' => $small, 'large' => $large, 'tag' => $tags  ];
            }
        }
        else {
            Log::debug($process->getErrorOutput());
            $rib = 'ERROR';
        }

        SimplePrivateEvent::dispatch('state', 'admin-inline-rib', [
            'timestamp' => Carbon::now()->format('Y-m-d H:i:s'),
            'state' => $rib === 'ERROR' ? null : $rib
        ]);

        return 0;
    }
}