<?php

namespace App\Classes\Dynamic;

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

use App\Classes\Dynamic;
use App\Models\Address;

/**
 * This method will generate the hub status for an upstream Host/RC/ZC
 *
 * Arg is a collection of arguments. We only understand
 * + name - name of file to give to remote
 */
class HubStats extends Dynamic
{
	private const LOGKEY = 'DHS';

	private string $name = '';

	public function __construct(private Address $ao,Collection $arg)
	{
		Log::debug(sprintf('%s:- Generating Hub Stats for [%s] with arguments',self::LOGKEY,$ao->ftn),['args'=>$arg]);
		$this->name = $arg->get('name');
	}

	public function __toString(): string
	{
		$date = Carbon::now()->yesterday()->endOfday();

		$r = Address::select([
			'a.id',
			'addresses.system_id',
			'addresses.zone_id',
			'addresses.region_id',
			'addresses.host_id',
			'addresses.node_id',
			'addresses.point_id',
			'addresses.hub_id',
			'addresses.role',
			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()
					->where('echomails.created_at','<',$date)
					->union(Address::UncollectedNetmailTotal()
						->where('netmails.created_at','<',$date)
					)
					->union(Address::UncollectedFilesTotal()
						->where('files.created_at','<',$date)
					),'a')
			->where('systems.active',true)
			->where('addresses.active',TRUE)
			->where('zones.active',TRUE)
			->where('domains.active',TRUE)
			->where('zones.id',$this->ao->zone_id)
			->join('addresses',['addresses.id'=>'a.id'])
			->join('systems',['systems.id'=>'addresses.system_id'])
			->join('zones',['zones.id'=>'addresses.zone_id'])
			->join('domains',['domains.id'=>'zones.domain_id'])
			->ftnOrder()
			->groupBy('addresses.system_id','a.id','addresses.zone_id','addresses.region_id','addresses.host_id','addresses.node_id','addresses.point_id','addresses.hub_id','addresses.role')
			->with(['system','zone.domain']);

		$header = "| %-12s | %4d | %3d | %3d | %16s | %5s | %5s |\r\n";

		$output = sprintf("Hub Status for [%s] as at [%s]\r\n",our_address($this->ao)->ftn,$date);
		$output .= "\r";
		$output .= "+--------------+------+-----+-----+------------------+-------+-------+\r\n";
		$output .= "| FTN          | ECHO | NET |FILES| LAST SESSION     |  MODE |AUTOHLD|\r\n";
		$output .= "+--------------+------+-----+-----+------------------+-------+-------+\r\n";

		$havedown = FALSE;
		$havehold = FALSE;

		foreach($r->get() as $o) {
			if ($o->uncollected_echomail > 10000)
				$o->uncollected_echomail = 9999;

			if ($o->uncollected_netmail > 10000)
				$o->uncollected_netmail = 9999;

			if ($o->uncollected_files > 10000)
				$o->uncollected_files = 9999;

			if ((! $havedown) && $o->is_down)
				$havedown = TRUE;

			if ((! $havehold) && $o->is_hold)
				$havehold = TRUE;

			$output .= sprintf($header,
				sprintf('%s %s',$o->ftn4d,$o->is_down ? 'd' : ($o->is_hold ? 'h' : ' ')),
				$o->uncollected_echomail ?? 0,
				$o->uncollected_netmail ?? 0,
				$o->uncollected_files ?? 0,
				$o->system->last_seen?->format('Y-m-d H:i') ?: '-',
				is_null($o->system->pollmode) ? 'HOLD' : ($o->system->pollmode ? 'CRASH' : 'DAILY'),
				$o->system->autohold ? 'YES' : 'NO');
		}

		$output .= "+--------------+------+-----+-----+------------------+-------+-------+\r\n";

		$output .= "\r\n";

		if ($havehold)
			$output .= "(h) Node is on HOLD status.\r\n";

		if ($havedown)
			$output .= "(d) Node is on DOWN status.\r\n";

		return $output;
	}

	public function getName(): string
	{
		return $this->name ?: 'hubstats.txt';
	}
}