<?php

namespace App\Console\Commands\Broadcast;

use App\Console\Commands\BaseCommand;
use Carbon\Carbon;
use App\Events\SimplePrivateEvent;
use App\Models\Asns;
use App\Helpers\ChartHandler;
use App\Helpers\ClickhouseHandler;
use App\Models\EventLease;

class BroadcastGoliathTraffic extends BaseCommand
{

    protected $signature = 'broadcast:goliath-traffic';

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

    protected $notEnterprise = true;

    public function handle()
    {
        // Query users for all logged in users, then get the associated organisations...
        $organisation_ids = EventLease::leftJoin('users', 'user_id', '=', 'users.id')
            ->where([
                ['leased_at', '>', Carbon::now()->subMinutes(2)],
                ['resource', '=', 'droppedTraffic']
            ])
            ->get()
            ->pluck('organisation_id');
            
        // Build our clickhouse handler
        $chh = new ClickhouseHandler(
            'default',
            null,
            null,
            null,
            null,
            'http://10.100.18.32:9000/'
        );


        foreach($organisation_ids as $id) {

            // Select all the ASNs for a given organisation
            $asns = Asns::where('organisation_id', '=', $id)->get()->pluck('asn');

            [$all_pps_event, $all_bps_event] = ChartHandler::goliathDropped($chh, $id === 1 ? [137409] : $asns, null, true, true, 60);
            
            SimplePrivateEvent::dispatch('dropped.pps', "goliathTraffic.$id", $all_pps_event);
            SimplePrivateEvent::dispatch('dropped.bps', "goliathTraffic.$id", $all_bps_event);
        }

        return 0;
    }
}