<?php

namespace App\Models;

use Carbon\Carbon;
use Exception;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

use App\Classes\FTN\Packet;
use App\Http\Controllers\DomainController;
use App\Traits\ScopeActive;

/**
 * @todo Need to stop this from happening:
 * In this example nn:3/1 can be defined 3 different ways.
 * +  id |  zone_id | region_id | host_id | node_id | point_id | status | role | system_id | hub_id
 * + ----+---------+-----------+---------+---------+----------+--------+------+-----------+--------
 * + 533 |       6 |         3 |       0 |       1 |        0 |        |    4 |         1 |
 * + 534 |       6 |         n |       3 |       1 |        0 |        |    2 |         1 |
 * + 535 |       6 |         0 |       3 |       1 |        0 |        |    2 |         1 |
 */
class Address extends Model
{
	private const LOGKEY = 'MA-';

	use ScopeActive,SoftDeletes;

	protected $with = ['zone'];

	// http://ftsc.org/docs/frl-1028.002
	public const ftn_regex = '([0-9]+):([0-9]+)/([0-9]+)(\.([0-9]+))?(@([a-z0-9\-_~]{0,8}))?';

	public const NODE_ZC		= 1<<0;		// Zone
	public const NODE_RC		= 1<<1;		// Region
	public const NODE_NC		= 1<<2;		// Host
	public const NODE_HC		= 1<<3;		// Hub
	public const NODE_ACTIVE	= 1<<4;		// Node
	public const NODE_PVT		= 1<<5;		// Pvt
	public const NODE_HOLD		= 1<<6;		// Hold
	public const NODE_DOWN		= 1<<7;		// Down
	public const NODE_POINT		= 1<<8;		// Point
	public const NODE_UNKNOWN	= 1<<15;	// Unknown

	public static function boot()
	{
		parent::boot();

		// For indexes when deleting, we need to change active to FALSE
		static::softDeleted(function($model) {
			Log::debug(sprintf('%s:Deleting [%d], updating active to FALSE',self::LOGKEY,$model->id));

			$model->active = FALSE;
			$model->save();
		});
	}

	/* SCOPES */

	public function scopeFTNOrder($query)
	{
		return $query
			->orderBy('region_id')
			->orderBy('host_id')
			->orderBy('node_id')
			->orderBy('point_id');
	}

	/* RELATIONS */

	/**
	 * Find children dependent on this record
	 */
	public function children()
	{
		// We have no session data for this address, by definition it has no children
		if (! $this->session('sespass'))
			return $this->hasMany(self::class,'id','void');

		if (! $this->session('default')) {
			switch ($this->role) {
				case self::NODE_ZC:
					$children = self::select('addresses.*')
						->where('zone_id',$this->zone_id);

					break;

				case self::NODE_RC:
					$children = self::select('addresses.*')
						->where('zone_id',$this->zone_id)
						->where('region_id',$this->region_id);

					break;

				case self::NODE_NC:
					$children = self::select('addresses.*')
						->where('zone_id',$this->zone_id)
						->where('region_id',$this->region_id)
						->where('host_id',$this->host_id);

					break;

				case self::NODE_HC:
					// Identify our children.
					$children = self::select('addresses.*')
						->where('hub_id',$this->id);

					break;

				case self::NODE_UNKNOWN:
				case self::NODE_ACTIVE:
				case self::NODE_POINT:
				case self::NODE_PVT:
					// Nodes dont have children, but must return a relationship instance
					return $this->hasOne(self::class,NULL,'void');

				default:
					throw new Exception('Unknown role: '.serialize($this->role));
			}

		} else {
			$children = self::select('addresses.*')
				->where('zone_id',$this->zone_id);
		}

		// Remove any children that we have session details for (SAME AS HC)
		$sessions = self::select('hubnodes.*')
			->join('system_zone',['system_zone.system_id'=>'addresses.system_id','system_zone.zone_id'=>'addresses.zone_id'])
			->join('addresses as hubnodes',['hubnodes.zone_id'=>'addresses.zone_id','hubnodes.id'=>'addresses.id'])
			->where('addresses.zone_id',$this->zone_id)
			->where('addresses.system_id','<>',$this->system_id)
			->whereIN('addresses.system_id',$children->get()->pluck('system_id'));

		// For each of the session, identify their children
		$session_kids = collect();
		foreach ($sessions->get() as $so)
			$session_kids = $session_kids->merge(($x=$so->children) ? $x->pluck('id') : []);

		// ZC's receive all mail, except for defined nodes, and defined hubs/hosts/rcs
		return $this->hasMany(self::class,'zone_id','zone_id')
			->whereIn('id',$children->get()->pluck('id')->toArray())
			->whereNotIn('id',$sessions->get()->pluck('id')->toArray())
			->whereNotIn('id',$session_kids->toArray())
			->where('system_id','<>',$this->system_id)
			->select('addresses.*')
			->orderBy('region_id')
			->orderBy('host_id')
			->orderBy('node_id')
			->orderBy('point_id')
			->with(['zone.domain']);
	}

	/**
	 * Echoareas this address is subscribed to
	 *
	 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
	 */
	public function echoareas()
	{
		return $this->belongsToMany(Echoarea::class)
			->withPivot(['subscribed']);
	}

	/**
	 * Echomails that this address has seen
	 *
	 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
	 */
	public function echomails()
	{
		return $this->belongsToMany(Echomail::class,'echomail_seenby')
			->withPivot(['sent_at','export_at','packet']);
	}

	public function echomail_from()
	{
		return $this->hasMany(Echomail::class,'fftn_id','id');
	}

	/**
	 * Files that this address has seen
	 *
	 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
	 */
	public function files()
	{
		return $this->belongsToMany(File::class,'file_seenby')
			->withPivot(['sent_at','export_at']);
	}

	/**
	 * Echoareas this address is subscribed to
	 *
	 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
	 */
	public function fileareas()
	{
		return $this->belongsToMany(Filearea::class)
			->withPivot(['subscribed']);
	}

	/**
	 * Who we send this systems mail to.
	 *
	 * @return Address|null
	 * @throws Exception
	 */
	public function parent(): ?Address
	{
		// If we are have session password, then we dont have a parent
		if ($this->session('sespass'))
			return $this;

		switch ($this->role) {
			// ZCs dont have parents, but we may have a default
			case self::NODE_ZC:
				if (($x=$this->zone->systems->where('pivot.default',TRUE))->count())
					return $x->first()->match($this->zone,255)->first();
				else
					return NULL;

			// RC
			case self::NODE_RC:
				$parent = self::where('zone_id',$this->zone_id)
					->where('region_id',0)
					->where('host_id',0)
					->where('node_id',0)
					->single();

				break;

			// Hosts
			case self::NODE_NC:
				// See if we have a RC
				$parent = self::where('zone_id',$this->zone_id)
					->where('region_id',$this->region_id)
					->where('host_id',0)
					->where('node_id',0)
					->single();

				if (! $parent) {
					// See if we have a RC
					$parent = self::where('zone_id',$this->zone_id)
						->where('region_id',0)
						->where('host_id',0)
						->where('node_id',0)
						->single();
				}

				break;

			// Hubs
			case self::NODE_HC:
			// Normal Nodes
			case self::NODE_ACTIVE:
				// If we are a child of a hub, then check our hub
				$parent = (($this->hub_id)
					? self::where('id',$this->hub_id)
					: self::where('zone_id',$this->zone_id)
					->where('region_id',$this->region_id)
					->where('host_id',$this->host_id)
					->where('node_id',0))
					->single();

				break;

			case self::NODE_UNKNOWN:
			case self::NODE_POINT:
			case self::NODE_DOWN:
				// @todo Points - if the boss is defined, we should return it.
				return NULL;

			default:
				throw new Exception('Unknown role: '.serialize($this->role));
		}

		return $parent?->parent();
	}

	public function system()
	{
		return $this->belongsTo(System::class);
	}

	public function zone()
	{
		return $this->belongsTo(Zone::class);
	}

	/* ATTRIBUTES */

	/**
	 * Render the node name in full 5D
	 *
	 * @return string
	 */
	public function getFTNAttribute(): string
	{
		return sprintf('%s@%s',$this->getFTN4DAttribute(),$this->zone->domain->name);
	}

	public function getFTN2DAttribute(): string
	{
		return sprintf('%d/%d',$this->host_id ?: $this->region_id,$this->node_id);
	}

	public function getFTN3DAttribute(): string
	{
		return sprintf('%d:%d/%d',$this->zone->zone_id,$this->host_id ?: $this->region_id,$this->node_id);
	}

	public function getFTN4DAttribute(): string
	{
		return sprintf('%s.%d',$this->getFTN3DAttribute(),$this->point_id);
	}

	public function getRoleNameAttribute(): string
	{
		switch ($this->role) {
			case self::NODE_ZC:
				return 'ZC';
			case self::NODE_RC:
				return 'RC';
			case self::NODE_NC:
				return 'NC';
			case self::NODE_HC:
				return 'HUB';
			case self::NODE_ACTIVE:
				return 'NODE';
			case self::NODE_POINT:
				return 'POINT';
			default:
				return '?';
		}
	}

	/* METHODS */

	/**
	 * Find a record in the DB for a node string, eg: 10:1/1.0
	 *
	 * @param string $address
	 * @param bool $create
	 * @param System|null $so
	 * @return Address|null
	 * @throws Exception
	 */
	public static function findFTN(string $address,bool $create=FALSE,System $so=NULL): ?self
	{
		$ftn = self::parseFTN($address);

		// Are we looking for a region address
		if (($ftn['f'] === 0) && $ftn['p'] === 0) {
			$o = (new self)->active()
				->select('addresses.*')
				->where('zones.zone_id',$ftn['z'])
				->where(function($q) use ($ftn) {
					return $q
						->where(function($q) use ($ftn) {
							return $q->where('region_id',$ftn['n'])
								->where('host_id',0);
						});
				})
				->where('node_id',$ftn['f'])
				->where('point_id',$ftn['p'])
				->join('zones',['zones.id'=>'addresses.zone_id'])
				->join('domains',['domains.id'=>'zones.domain_id'])
				->where('zones.active',TRUE)
				->where('domains.active',TRUE)
				->where('addresses.active',TRUE)
				->when($ftn['d'],function($query,$domain) {
					$query->where('domains.name',$domain);
				})
				->when((! $ftn['d']),function($query) {
					$query->where('zones.default',TRUE);
				})
				->single();

			if ($o && $o->system->active)
				return $o;
		}

		$o = (new self)->active()
			->select('addresses.*')
			->where('zones.zone_id',$ftn['z'])
			->where(function($q) use ($ftn) {
				return $q->where(function($qq) use ($ftn) {
					return $qq
						->where('region_id',$ftn['n'])
						->where('host_id',0);
					})
					->orWhere(function($qq) use ($ftn) {
					return $qq
						->where('host_id',$ftn['n']);
					});
			})
			->where('node_id',$ftn['f'])
			->where('point_id',$ftn['p'])
			->join('zones',['zones.id'=>'addresses.zone_id'])
			->join('domains',['domains.id'=>'zones.domain_id'])
			->where('zones.active',TRUE)
			->where('domains.active',TRUE)
			->where('addresses.active',TRUE)
			->when($ftn['d'],function($query,$domain) {
				$query->where('domains.name',$domain);
			})
			->when((! $ftn['d']),function($query) {
				$query->where('zones.default',TRUE);
			})
			->single();

		if ($create) {
			if (! $so)
				throw new Exception(sprintf('%s:AKA create requested for [%s], but system not provided',self::LOGKEY,$address));

			if (! $ftn['d']) {
				Log::alert(sprintf('%s:! Refusing to create address [%s] no domain available',self::LOGKEY,$address));

				return NULL;
			}

			Log::debug(sprintf('%s:Creating AKA [%s] for [%s]',self::LOGKEY,$address,$so->name));

			// Check Domain exists
			Domain::unguard();
			$do = Domain::singleOrNew(['name'=>$ftn['d']]);
			Domain::reguard();

			if (! $do->exists) {
				$do->public = TRUE;
				$do->active = TRUE;
				$do->notes = 'Auto created';
				$do->save();
			}

			// Create zone
			Zone::unguard();
			$zo = Zone::singleOrNew(['domain_id'=>$do->id,'zone_id'=>$ftn['z']]);
			Zone::reguard();

			if (! $zo->exists) {
				$zo->active = TRUE;
				$zo->notes = 'Auto created';
				$zo->system_id = System::where('name','Discovered System')->single()->id;
				$do->zones()->save($zo);
			}

			if (! $zo->active || ! $do->active) {
				Log::alert(sprintf('%s:! Refusing to create address [%s] in disabled zone or domain',self::LOGKEY,$address));

				return NULL;
			}

			// Create Address, assigned to $so
			$o = new self;
			$o->active = TRUE;
			$o->zone_id = $zo->id;
			$o->region_id = 0;
			$o->host_id = $ftn['n'];
			$o->node_id = $ftn['f'];
			$o->point_id = $ftn['p'];
			$o->role = self::NODE_UNKNOWN;
			$so->addresses()->save($o);
		}

		return ($o && $o->system->active) ? $o : NULL;
	}

	/**
	 * Create an activation code for this address
	 *
	 * @param User $uo
	 * @return string
	 */
	public function set_activation(User $uo): string
	{
		return sprintf('%x:%s',
			$this->id,
			substr(md5(sprintf('%d:%x',$uo->id,timew($this->updated_at))),0,10)
		);
	}

	/**
	 * Check the user's activation code for this address is correct
	 *
	 * @param User $uo
	 * @param string $code
	 * @return bool
	 */
	public function check_activation(User $uo,string $code): bool
	{
		try {
			Log::info(sprintf('%s:Checking Activation code [%s] invalid for user [%d]',self::LOGKEY,$code,$uo->id));

			return ($code == $this->set_activation($uo));

		} catch (\Exception $e) {
			Log::error(sprintf('%s:! Activation code [%s] invalid for user [%d]',self::LOGKEY,$code,$uo->id));

			return FALSE;
		}
	}

	/**
	 * Echomail waiting to be sent to this system
	 *
	 * @return Collection
	 */
	public function echomailWaiting(): Collection
	{
		return $this->echomails()
			->whereNull('echomail_seenby.sent_at')
			->whereNotNull('echomail_seenby.export_at')
			->get();
	}

	/**
	 * Files waiting to be sent to this system
	 *
	 * @return Collection
	 */
	public function filesWaiting(): Collection
	{
		return $this->files()
			->whereNull('file_seenby.sent_at')
			->whereNotNull('file_seenby.export_at')
			->get();
	}

	/**
	 * Get echomail for this node
	 *
	 * @param bool $update
	 * @param Collection|null $echomail
	 * @return Packet|null
	 */
	public function getEchomail(bool $update=TRUE,Collection $echomail=NULL): ?Packet
	{
		$pkt = NULL;
		if ($echomail)
			return $this->getPacket($echomail);

		if (($x=$this->echomailWaiting())
			->count())
		{
			Log::debug(sprintf('%s:= Got [%d] echomails for [%s] for sending',self::LOGKEY,$x->count(),$this->ftn));

			$pkt = $this->getPacket($x);

			if ($pkt && $pkt->count() && $update)
				DB::table('echomail_seenby')
					->whereIn('echomail_id',$x->pluck('id'))
					->where('address_id',$this->id)
					->whereNull('sent_at')
					->whereNull('packet')
					->whereNotNull('echomail_seenby.export_at')
					->update(['sent_at'=>Carbon::now(),'packet'=>$pkt->name]);
		}

		return $pkt;
	}

	/**
	 * Get netmail for this node (including it's children)
	 *
	 * @param bool $update
	 * @return Packet|null
	 */
	public function getNetmail(bool $update=TRUE): ?Packet
	{
		$pkt = NULL;

		if (($x=$this->netmailWaiting())
			->count())
		{
			Log::debug(sprintf('%s:= Got [%d] netmails for [%s] for sending',self::LOGKEY,$x->count(),$this->ftn));

			$pkt = $this->getPacket($x);

			if ($pkt && $pkt->count() && $update)
				DB::table('netmails')
					->whereIn('id',$x->pluck('id'))
					->update(['sent_at'=>Carbon::now(),'sent_pkt'=>$pkt->name]);
		}

		return $pkt;
	}

	/**
	 * Return a packet of mail
	 *
	 * @param Collection $c of message models (Echomail/Netmail)
	 * @return Packet|null
	 */
	private function getPacket(Collection $c): ?Packet
	{
		$ao = Setup::findOrFail(config('app.id'))->system->match($this->zone)->first();

		// If we dont match on the address, we cannot pack mail for that system
		if (! $ao)
			return NULL;

		$o = new Packet($ao,$this);

		// $oo = Netmail/Echomail Model
		foreach ($c as $oo)
			$o->addMail($oo->packet($this));

		return $o;
	}

	/**
	 * Netmail waiting to be sent to this system
	 *
	 * @return Collection
	 */
	public function netmailWaiting(): Collection
	{
		return Netmail::whereIn('tftn_id',(($x=$this->children) ? $x->pluck('id') : collect())->push($this->id))
			->whereNull('sent_at')
			->get();
	}

	/**
	 *
	 * Parse a string and split it out as an FTN array
	 *
	 * @param string $ftn
	 * @return array
	 * @throws Exception
	 */
	public static function parseFTN(string $ftn): array
	{
		if (! preg_match(sprintf('#^%s$#',self::ftn_regex),strtolower($ftn),$matches))
			throw new Exception('Invalid FTN: '.$ftn);

		// Check our numbers are correct.
		foreach ([1,2,3] as $i) {
			if ((! is_numeric($matches[$i])) || ($matches[$i] > DomainController::NUMBER_MAX))
				throw new Exception('Invalid FTN: '.$ftn);
		}

		if (isset($matches[5]) AND ((! is_numeric($matches[$i])) || ($matches[5] > DomainController::NUMBER_MAX)))
			throw new Exception('Invalid FTN: '.$ftn);

		return [
			'z'=>(int)$matches[1],
			'n'=>(int)$matches[2],
			'f'=>(int)$matches[3],
			'p'=>isset($matches[5]) && $matches[5] ? (int)$matches[5] : 0,
			'd'=>$matches[7] ?? NULL
		];
	}

	/**
	 * Retrieve the address session details/passwords
	 *
	 * @param string $type
	 * @return string|null
	 */
	public function session(string $type): ?string
	{
		return ($x=$this->system->sessions->where('id',$this->zone_id)->first()) ? $x->pivot->{$type} : NULL;
	}
}