<?php

namespace App\Jobs;

use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Notification;

use App\Classes\FTN\Message;
use App\Models\{Address,Domain};
use App\Notifications\Echomails\AbsentNodes;
use App\Notifications\Emails\NodeMarkedDown as NodeMarkedDownEmail;
use App\Notifications\Netmails\NodeMarkedDown as NodeMarkedDownNetmail;
use App\Notifications\Emails\NodeMarkedHold as NodeMarkedHoldEmail;
use App\Notifications\Netmails\NodeMarkedHold as NodeMarkedHoldNetmail;
use App\Notifications\Emails\NodeDelisted as NodeDelistedEmail;
use App\Notifications\Netmails\NodeDelisted as NodeDelistedNetmail;

class AddressIdle implements ShouldQueue
{
	use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

	private const LOGKEY = 'JAI';

	private ?Address $ao;	// System address
	private Domain $do;		// Domain we are processing

	/**
	 * Create a new job instance.
	 */
	public function __construct(Domain $do,Address $ao=NULL)
	{
		$this->do = $do;
		$this->ao = $ao;
	}

	/**
	 * Execute the job.
	 */
	public function handle(): void
	{
		$result = collect();

		// Delist DOWN nodes
		foreach ($this->old($this->do,config('fido.idle.delist'),Address::NODE_DOWN,$this->ao) as $ao) {
			// Only delist system that has been marked down
			// Only mark delist them if its been 7 days since they were marked DOWN
			if ((! $ao->is_down) || ($ao->updated_at->isPast(Carbon::now()->subWeek())))
				continue;

			Log::info(sprintf('%s:- Delisting [%s], not seen for [%d] days',self::LOGKEY,$ao->ftn,config('fido.idle.delist')));
			$contact = FALSE;

			// Remove echomail not collected from echomail_seenby
			DB::table('echomail_seenby')
				->where('address_id',$ao->id)
				->whereNotNull('export_at')
				->whereNull('sent_at')
				->delete();

			// Remove FLAG_INTRANSIT from netmail that hasnt been delivered
			DB::table('netmails')
				->where('tftn_id',$ao->id)
				->whereRaw(sprintf('(flags & %d) > 0',Message::FLAG_INTRANSIT))
				->update(['flags'=>DB::raw(sprintf('(flags & ~%d)',Message::FLAG_INTRANSIT))]);

			// Remove files not collected
			DB::table('file_seenby')
				->where('address_id',$ao->id)
				->whereNotNull('export_at')
				->whereNull('sent_at')
				->delete();

			// Remove subscribed echoareas
			$ao->echoareas()->detach();

			// Remove subscribed fileareas
			$ao->fileareas()->detach();

			$ao->active = FALSE;
			$ao->validated = FALSE;
			$ao->save();

			// Email Alert
			if ($ao->system->users->count()) {
				Notification::send($ao->system->users,new NodeDelistedEmail($ao->withoutRelations()));
				$contact = TRUE;
			}

			// Netmail Alert (to othernet network address)
			if ($ao->system->uncommon()->count()) {
				Notification::route('netmail',$ao->system->uncommon()->first()->withoutRelations())->notify(new NodeDelistedNetmail($ao->withoutRelations()));
				$contact = TRUE;
			}

			$ao->contacted = (! $contact);
			$result->push($ao);
		}

		// Mark nodes DOWN
		foreach ($this->old($this->do,config('fido.idle.down'),Address::NODE_HOLD,$this->ao) as $ao) {
			Log::info(sprintf('%s:- Marking [%s] as DOWN, not seen for [%d] days',self::LOGKEY,$ao->ftn,config('fido.idle.down')));
			$contact = FALSE;

			// Email Alert
			if ($ao->system->users->count()) {
				Notification::send($ao->system->users,new NodeMarkedDownEmail($ao->withoutRelations()));
				$contact = TRUE;
			}

			// Netmail Alert (to othernet network address)
			if ($ao->system->uncommon()->count()) {
				Notification::route('netmail',$ao->system->uncommon()->first()->withoutRelations())->notify(new NodeMarkedDownNetmail($ao->withoutRelations()));
				$contact = TRUE;
			}

			// Mark as DOWN
			$ao->role &= ~Address::NODE_HOLD;
			$ao->role |= Address::NODE_DOWN;
			$ao->save();

			$ao->contacted = (! $contact);
			$result->push($ao);
		}

		// Mark nodes as HOLD
		foreach ($this->old($this->do,config('fido.idle.hold'),0,$this->ao) as $ao) {
			// Ignore any systems already marked hold or down
			if ($ao->role & (Address::NODE_DOWN|Address::NODE_HOLD))
				continue;

			$contact = FALSE;

			Log::info(sprintf('%s:- Marking [%s] as HOLD, not seen for [%d] days',self::LOGKEY,$ao->ftn,config('fido.idle.hold')));

			// Email Alert
			if ($ao->system->users->count()) {
				Notification::send($ao->system->users,new NodeMarkedHoldEmail($ao->withoutRelations()));
				$contact = TRUE;
			}

			// Netmail Alert (to othernet network address)
			if ($ao->system->uncommon()->count()) {
				Notification::route('netmail',$ao->system->uncommon()->first()->withoutRelations())->notify(new NodeMarkedHoldNetmail($ao->withoutRelations()));
				$contact = TRUE;
			}

			// Mark as DOWN
			$ao->role |= Address::NODE_HOLD;
			$ao->save();

			$ao->contacted = (! $contact);
			$result->push($ao);
		}

		if ($result->count())
			Notification::route('echomail',$this->do->nodestatusarea)->notify(new AbsentNodes($result));
	}

	private function old(Domain $do,int $days,int $flags=0,Address $ao=NULL): Collection
	{
		$age = Carbon::now()->subDays($days)->endOfDay();

		return Address::select([
			'a.id',
			'a.system_id',
			'a.zone_id',
			'addresses.region_id',
			'a.host_id',
			'a.node_id',
			'a.point_id',
			'addresses.active',
			'addresses.hub_id',
			'addresses.role',
			'addresses.updated_at',
			DB::raw('sum(a.uncollected_echomail) as uncollected_echomail'),
			DB::raw('sum(a.uncollected_netmail) as uncollected_netmail'),
			DB::raw('sum(a.uncollected_files) as uncollected_files')
		])
			->from(
				Address::UncollectedEchomailTotal()
					->union(Address::UncollectedNetmailTotal())
					->union(Address::UncollectedFilesTotal()),'a')
			->where('systems.active',TRUE)
			->where('addresses.active',TRUE)
			->where('zones.active',TRUE)
			->where('domains.active',TRUE)
			->whereNotIn('a.id',our_address()->pluck('id'))
			->when($ao,fn($query)=>$query->where('addresses.id',$ao->id))
			->where('last_session','<',$age)
			->where('domains.id',$do->id)
			->whereRaw(sprintf('((role IS NULL) OR ((role & %d) > 0))',$flags))
			->join('addresses',['addresses.id'=>'a.id'])
			->join('systems',['systems.id'=>'a.system_id'])
			->join('zones',['zones.id'=>'addresses.zone_id'])
			->join('domains',['domains.id'=>'zones.domain_id'])
			->ftnOrder()
			->groupBy('a.system_id','a.id','a.zone_id','addresses.region_id','a.host_id','a.node_id','a.point_id','addresses.hub_id','addresses.role','addresses.active','addresses.updated_at')
			->with(['system','zone.domain'])
			->dontCache()
			->get();
	}
}