<?php

namespace App\Models;

use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Jenssegers\Mongodb\Eloquent\Model;
use Jenssegers\Mongodb\Eloquent\SoftDeletes;

use App\Interfaces\Packet;

final class OldEchomail extends Model
{
	use SoftDeletes;

	private const LOGKEY = 'ME-';
	protected $table = 'echomails';

	protected $collection = FALSE;

	protected $casts = [ 'kludges' => 'json' ];

	private const cast_utf8 = [
		'to',
		'from',
		'subject',
		'msg',
		'origin',
		'tearline',
		'tagline',
	];
	protected $dates = ['datetime'];

	public static function resolveConnection($connection = null)
	{
		return static::$resolver->connection('mongodb');
	}

	/* RELATIONS */

	public function echoarea()
	{
		return $this->belongsTo(Echoarea::class);
	}

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

	/* ATTRIBUTES */

	public function getKludgesAttribute(?string $value): Collection
	{
		return collect($this->castAttribute('kludges',$value));
	}

	public function getPathAttribute(?array $value): Collection
	{
		if (is_null($value))
			return collect();

		return Address::whereIn('id',$value)
			->orderBy(DB::raw(sprintf("position (id::text in '(%s)')",join(',',$value))))
			->get();
	}

	public function getSeenByAttribute(?array $value): Collection
	{
		if (is_null($value))
			return collect();

		return Address::whereIn('id',$value)->get();
	}
}