<?php

namespace App\Notifications\Netmails\Filefix;

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

use App\Notifications\Netmails;
use App\Models\{Filearea,Netmail};
use Illuminate\Support\Str;
use App\Traits\{MessagePath,PageTemplate};

class Filelist extends Netmails
{
	use MessagePath,PageTemplate;

	private const LOGKEY = 'FCL';

	private Filearea $fa;
	private int $days;

	/**
	 * Reply to a filefix FILELIST commands.
	 *
	 * @param Filearea $fa
	 * @param int $days
	 */
	public function __construct(Netmail $mo,Filearea $fa,int $days=30)
	{
		parent::__construct();

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

	/**
	 * 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 [%s] FILE LIST processed',self::LOGKEY,$ao->ftn));

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

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

		$msg->addText(sprintf("Filearea [%s] has the following files in the last %d days:\r\r",$this->fa->name,$this->days));

		$files = $this->fa
			->files()
			->orderBy('datetime')
			->where('datetime','>',Carbon::now()->subDays($this->days)->startOfDay());

		if ($files->count()) {
			$msg->addText(sprintf(":-%s-:-%s-:-%s-:\r",
				str_repeat('-',15),
				str_repeat('-',44),
				str_repeat('-',8),
			));
			$msg->addText(sprintf(": %-15s : %-44s : %8s :\r",'FILE','DESCRIPTION','SIZE(mb)'));
			$msg->addText(sprintf(":-%s-:-%s-:-%s-:\r",
				str_repeat('-',15),
				str_repeat('-',44),
				str_repeat('-',8),
			));

			foreach ($files->get() as $fo) {
				$msg->addText(sprintf(": %-15s : %-44s : %8s :\r",
					$fo->name,
					Str::limit($fo->desc,44-3),
					number_format($fo->size/1024/1024,3),
				));
			}

			$msg->addText(sprintf(":-%s-:-%s-:-%s-:\r",
				str_repeat('-',15),
				str_repeat('-',44),
				str_repeat('-',8),
			));

		} else {
			$msg->addText(sprintf('No files in [%s]',$this->fa->name));
		}

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

		$o->save();

		return $o;
	}
}