<?php

namespace App\Notifications\Channels;

use Illuminate\Notifications\Notification;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;

class MatrixChannel
{
	use interactsWithQueue;

	private const LOGKEY = 'CNM';

	/**
	 * Create a new Matrix channel instance.
	 */
	public function __construct()
	{
	}

	/**
	 * Send the given notification.
	 *
	 * @param mixed $notifiable
	 * @param \Illuminate\Notifications\Notification $notification
	 * @return \Psr\Http\Message\ResponseInterface|void
	 */
	public function send($notifiable,Notification $notification)
	{
		if (! $room = $notifiable->routeNotificationFor('matrix',$notification))
			return;

		try {
			$o = $notification->toMatrix($notifiable);

		// @todo Check this exception works as expected (putting the job back on the queue when the user doesnt exist), else it might need to go in Matrix/Echomail
		} catch (\Exception $e) {
			Log::info(sprintf('%s:= Exception [%s] posting to Matrix, putting job back on queue for [%s]',self::LOGKEY,$e->getMessage(),$room));
			$this->release();
			return;
		}

		// @todo Be nice to get the message ID for debugging
		Log::info(sprintf('%s:= Posted echomail to Matrix [%s]',self::LOGKEY,$room),['o'=>$o]);
	}
}