<?php

namespace App\Modules\Network\Commands;

use Log;
use Illuminate\Support\Facades\Notification;
use App\Notifications\SlackNotification;
use Carbon\Carbon;

use App\Modules\Network\Models\Goliath\GoliathAppliance;
use App\Models\ApiEvent;

class GoliathMonitorAgent extends \App\Console\Commands\BaseCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'goliath:monitor-agent';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Monitors goliath appliances to see whether the agents are active.';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        try {
            $appliances = GoliathAppliance::leftJoin('goliath_metro', 'goliath_metro.id', '=', 'goliath_appliances.metro_id')
                ->leftJoin('goliath_subregions', 'goliath_subregions.id', '=', 'goliath_appliances.subregion_id')
                ->leftJoin('goliath_regions', 'goliath_regions.id', '=', 'goliath_appliances.region_id')
                ->select('goliath_appliances.id', 'address', 'goliath_metro.name as metro', 'goliath_subregions.name as subregion', 'goliath_regions.name as region')
                ->get();

            $relevant_events = ApiEvent::where([
                    ['created_at', '>', Carbon::now()->subMinute()],
                    ['description', '=', 'Method: GET'],
                    ['payload', 'LIKE', '{"appliance_id":"%'],
                    ['route', 'LIKE', 'api/goliath/data/%']
                ])
                ->whereIn('ip', $appliances->pluck('address'))
                ->get();

            $missing_callouts = [];

            foreach($appliances as $appliance) {
                if(count($relevant_events->where('ip', '=', $appliance->address)) === 0) {
                    $missing_callouts[] = $appliance;
                }
            }

            foreach($missing_callouts as $missing) {
                Notification::route('slack', env('SLACK_HOOK'))->notify(new SlackNotification(
                    "The agent for an appliance of ID: $missing->id has not been seen in the past minute. Please investigate. Facility: $missing->metro, subregion: $missing->subregion, region: $missing->region"
                ));
            }
        }
        catch(Exception $ex) {}

        return 0;
    }
}