<?php

namespace app\foreignone\files;

use engine\Model;

class WFFArchiveFile
    extends Model
    implements FileInterface
{
    const DB_TABLE = 'wff_collection';

    public int $id;
    public int $parentId;
    public string $title;
    public string $documentId;
    public string $path;
    public int $filesCount;
    public int $size;
    public string $type;

    public function getTitleHtml(): ?string {
        return null;
    }

    public function getId(): string {
        return (string)$this->id;
    }

    public function getTitle(): string {
        return $this->title;
    }

    public function getDocumentId(): string {
        return $this->type == 'folder' ? str_replace('_', ' ', basename($this->path)) : $this->documentId;
    }

    public function isTargetBlank(): bool {
        return $this->type == 'file';
    }

    public function getSubtitle(): ?string {
        return null;
    }

    public function getUrl(): string {
        global $config;
        return $this->type == 'folder'
            ? "/files/wff/{$this->id}/"
            : "https://{$config['files_domain']}/NSA Friedman Documents/{$this->path}";
    }

    public function getMeta(?string $hl_matched = null): array {
        if ($this->type == 'folder') {
            if (!$this->parentId)
                return [];
            return [
                'items' => [
                    highlightSubstring($this->getDocumentId(), $hl_matched),
                    langNum('files_count', $this->filesCount)
                ]
            ];
        }
        return [
            'inline' => false,
            'items' => [
                highlightSubstring('Document '.$this->documentId, $hl_matched),
                sizeString($this->size),
                'PDF'
            ]
        ];
    }

    public function getSize(): ?int {
        return $this->type == 'file' ? $this->size : null;
    }

    public function getIcon(): string {
        return $this->type; // it's either 'file' or 'folder'
    }

    public function getFullText(): ?string {
        if ($this->type != 'file')
            return null;
        $db = getDB();
        return $db->result($db->query("SELECT text FROM wff_texts WHERE wff_id=?", $this->id));
    }


    /**
     * Static methods
     */

    /**
     * @return WFFArchiveFile[]
     */
    public static function getAll(): array {
        $db = getDB();
        $q = $db->query("SELECT * FROM wff_collection");
        return array_map(static::create_instance(...), $db->fetchAll($q));
    }

    /**
     * @param int|int[]|null $parent_id
     * @return array
     */
    public static function getList(int|array|null $parent_id = null): array {
        $db = getDB();

        $where = [];
        $args = [];

        if (!is_null($parent_id)) {
            if (is_int($parent_id)) {
                $where[] = "parent_id=?";
                $args[] = $parent_id;
            } else {
                $where[] = "parent_id IN (".implode(", ", $parent_id).")";
            }
        }
        $sql = "SELECT * FROM wff_collection";
        if (!empty($where))
            $sql .= " WHERE ".implode(" AND ", $where);
        $sql .= " ORDER BY title";
        $q = $db->query($sql, ...$args);

        return array_map(static::create_instance(...), $db->fetchAll($q));
    }

    /**
     * @param int[] $ids
     * @return WFFArchiveFile[]
     */
    public static function getItemsById(array $ids): array {
        $db = getDB();
        $q = $db->query("SELECT * FROM wff_collection WHERE id IN (".implode(',', $ids).")");
        return array_map(static::create_instance(...), $db->fetchAll($q));
    }

    /**
     * @param int $folder_id
     * @param bool $with_parents
     * @return static|static[]|null
     */
    public static function getFolder(int $folder_id, bool $with_parents = false): static|array|null
    {
        $db = getDB();
        $q = $db->query("SELECT * FROM wff_collection WHERE id=?", $folder_id);
        if (!$db->numRows($q))
            return null;
        $item = new WFFArchiveFile($db->fetch($q));
        if ($item->type != 'folder')
            return null;
        if ($with_parents) {
            $items = [$item];
            if ($item->parentId) {
                $parents = static::getFolder($item->parentId, with_parents: true);
                if ($parents !== null)
                    $items = array_merge($items, $parents);
            }
            return $items;
        }
        return $item;
    }
}
