<?php

namespace App\Classes\File;

use App\Classes\Node;
use App\Models\Address;
use App\Models\File;
use App\Classes\FTN\Tic as FTNTic;

final class Tic extends Send
{
	/** @var int Our internal position counter */
	private int $readpos;
	private Address $ao;
	private string $tic;

	/**
	 * @throws \Exception
	 */
	public function __construct(File $file,Address $ao,int $type)
	{
		parent::__construct();

		$this->f = $file;
		$this->ao = $ao;
		$this->ftype = ((($type&0xff)<<8)|self::IS_TIC);
		$this->readpos = 0;

		$this->tic = FTNTic::generate($ao,$file);
	}

	public function __get($key) {
		switch ($key) {
			case 'dbids':
				return collect([$this->f->id]);

			case 'name':
				return sprintf('%08x',timew($this->f->created_at));

			case 'nameas':
				return sprintf('%s.tic',$this->name);

			case 'mtime':
				return $this->f->datetime->timestamp;

			case 'size':
				return strlen($this->tic);

			case 'type':
				return ($this->ftype&0xff00)>>8;

			default:
				return parent::__get($key);
		}
	}

	public function close(bool $successful,Node $node): void
	{
		if ($successful)
			$this->complete = TRUE;
	}

	public function feof(): bool
	{
		return ($this->readpos === $this->size);
	}

	public function open(string $compress=''): bool
	{
		return TRUE;
	}

	public function read(int $length): string
	{
		$result = substr($this->tic,$this->readpos,$length);
		$this->readpos += strlen($result);

		return $result;
	}

	public function seek(int $pos): bool
	{
		$this->readpos = ($pos < $this->size) ? $pos : $this->size;
		return TRUE;
	}
}