<?php

namespace App\Models;

use Carbon\Carbon;
use Jenssegers\Mongodb\Eloquent\Model;
use Jenssegers\Mongodb\Eloquent\SoftDeletes;

use App\Classes\FTN\Message;
use App\Interfaces\Packet;
use App\Traits\UseMongo;

class Netmail extends Model implements Packet
{
	use SoftDeletes,UseMongo;

	protected $dates = ['datetime','sent_at'];

	/* RELATIONS */

	public function fftn()
	{
		return $this
			->setConnection('pgsql')
			->belongsTo(Address::class)
			->withTrashed();
	}

	public function tftn()
	{
		return $this
			->setConnection('pgsql')
			->belongsTo(Address::class);
	}

	/* METHODS */

	/**
	 * Return this model as a packet
	 */
	public function packet(Address $ao): Message
	{
		// @todo Dont bundle mail to nodes that have been disabled, or addresses that have been deleted
		$o = new Message;

		$o->header = [
			'onode' => $this->fftn->node_id,
			'dnode' => $ao->node_id,
			'onet' => $this->fftn->host_id,
			'dnet' => $ao->host_id,
			'flags' => 0,	// @todo?
			'cost' => 0,
			'date'=>$this->datetime->format('d M y  H:i:s'),
		];

		$o->tzutc = $this->datetime->utcOffset($this->tzoffset)->getOffsetString('');
		$o->user_to = $this->to;
		$o->user_from = $this->from;
		$o->subject = $this->subject;

		// INTL kludge
		// @todo Point handling FMPT/TOPT
		$o->intl = sprintf('%s %s',$this->tftn->ftn3d,$this->fftn->ftn3d);
		$o->flags = $this->flags;

		$o->msgid = sprintf('%s %08x',$this->fftn->ftn3d,crc32($this->id));
		if ($this->reply)
			$o->reply = $this->reply;

		$o->message = $this->msg;

		if ($this->tagline)
			$o->message .= $this->tagline;

		if ($this->tearline)
			$o->tearline .= $this->tearline;

		// VIA kludge
		$via = $this->via ?: collect();
		$via->push(
			sprintf('%s @%s.UTC %s %d.%d/%s %s',
				$this->fftn->ftn3d,
				Carbon::now()->utc()->format('Ymd.His'),
				Setup::PRODUCT_NAME,
				Setup::PRODUCT_VERSION_MAJ,
				Setup::PRODUCT_VERSION_MIN,
				(new Setup)->version,
				Carbon::now()->format('Y-m-d'),
		));

		$o->via = $via;

		return $o;
	}
}