<?php

namespace App\Notifications\Netmails\Filefix;

use Illuminate\Support\Facades\Log;

use App\Notifications\Netmails;
use App\Models\Netmail;
use App\Traits\{MessagePath,PageTemplate};

class AreaList extends Netmails
{
	use MessagePath,PageTemplate;

	private const LOGKEY = 'FCL';

	private Netmail $mo;

	/**
	 * Reply to a filefix AREALIST commands.
	 *
	 * @param Netmail $mo
	 */
	public function __construct(Netmail $mo)
	{
		parent::__construct();

		$this->mo = $mo->withoutRelations();
	}

	/**
	 * Get the mail representation of the notification.
	 *
	 * @param mixed $notifiable
	 * @return Netmail
	 * @throws \Exception
	 */
	public function toNetmail(object $notifiable): Netmail
	{
		$o = $this->setupNetmail($notifiable);
		$ao = $notifiable->routeNotificationFor(static::via);

		Log::info(sprintf('%s:+ Responding to filefix for a node [%s] LIST processed',self::LOGKEY,$ao->ftn));

		$o->to = $this->mo->from;
		$o->replyid = $this->mo->msgid;
		$o->subject = 'Filefix - List';

		// Message
		$msg = $this->page(FALSE,'Filefix');

		$msg->addText("Here are the list of available filereas:\r\r\r\r");

		$areas = $ao->domain
			->fileareas
			->filter(fn($item)=>$item->active && ($item->can_read($ao->security) || $item->can_write($ao->security)));

		if ($areas->count()) {
			$msg->addText(sprintf(":---:-%s-:-%s-:-%s-:\r",
				str_repeat('-',10),
				str_repeat('-',48),
				str_repeat('-',5),
			));
			$msg->addText(sprintf(":   : %-10s : %-48s : %-5s :\r",'AREA','DESCRIPTION','FILES'));
			$msg->addText(sprintf(":---:-%s-:-%s-:-%s-:\r",
				str_repeat('-',10),
				str_repeat('-',48),
				str_repeat('-',5),
			));

			foreach ($areas as $eao) {
				$msg->addText(sprintf(":%s%s%s: %-10s : %-48s : %5d :\r",
					($x=$ao->fileareas->contains($eao)) ? '*' : ' ',
					(! $x ? '+' : ' '),
					($eao->can_read($ao->security) && (! $eao->can_write($ao->security)))
						? 'R'
						: (((! $eao->can_read($ao->security)) && $eao->can_write($ao->security)) ? 'W' : ' '),
					$eao->name,
					$eao->description,
					$eao->files()->count(),
				));
			}

			$msg->addText(sprintf(":---:-%s-:-%s-:-%s-:\r",
				str_repeat('-',10),
				str_repeat('-',48),
				str_repeat('-',5),
			));

			$msg->addText("\r'*' = Subscribed, '+' = available, 'R' = read only, 'W' = write only\r");

		} else {
			$msg->addText(sprintf('No areas available to you from domain [%s]',$ao->domain->name));
		}

		$o->msg = $msg->render();
		$o->set_tagline = 'Why did the chicken cross the road? The robot programmed it.';

		$o->save();

		return $o;
	}
}