<?php

namespace Mnv\Core\Filesystem;

use Mnv\Http\File;

/**
 * Class FileTree
 * @package Mnv\Core\Files
 */
class FileTree extends Filesystem
{
    /** @var array|string[]  */
    private array $allowed_extensions = array("tpl", "css", "js");

    /** @var array|string[]  */
    private array $hidden = array("favicon", "fonts", "images", "img");


    public function __construct(string $directory)
    {
        $this->realPath = GLOBAL_ROOT . "/themes/" . $directory;
    }

    /**
     * сохранение файла
     *
     * @param array $file
     * @return bool
     */
    public function save(array $file): bool
    {
        $type = $this->extension($file['path']);
        if (!in_array($type, $this->allowed_extensions, true)) {
           return false;
        }

        if (!$this->exists($this->realPath . $file['path']) || !$this->isWritable($this->realPath . $file['path'])) {
            return false;
        }

        $file['content'] = stripslashes($file['content']);
        if ($this->put($this->realPath . $file['path'], $file['content'])) {
            return true;
        }

        return false;
    }

    /**
     * чтение файла
     *
     * @param array $file
     * @return false|string
     */
    public function read(array $file)
    {
        $type = $this->extension($file['path']); // tpl

        if (!in_array($type, $this->allowed_extensions, true)) {
            return false;
        }
        if (!$this->exists($this->realPath . $file['path'])) {
            return false;
        }
        $content = $this->sharedGet($this->realPath . $file['path']);
        if (!is_writable($this->realPath. $file['path'])) {
            return false;
        }

        return $content;
    }

    /**
     * получение списка дерева папок и файлов
     *
     * @param string|null $path
     * @return string
     */
    public function all(?string $path): string
    {

        $resultList = '';

        $postDir = $this->realPath . $path;
        if ($this->exists($postDir)) {
            $directories = $this->directories($postDir);
            $resultList .=  "<ul class='jqueryFileTree'>";
            foreach ($directories as $directory) {
                $directoryName = $this->name($directory);
//                if (!in_array($directoryName, $this->hidden, true)) {
                    $resultList .= "<li class=\"directory collapsed\"><a rel=\"" . $path . $directoryName . "/\">" . $directoryName . "</a></li>";
//                }

            }
            $files = $this->files($postDir, false);
            foreach ($files as $file) {
                if (in_array($file->getExtension(), $this->allowed_extensions, true)) {
                    $resultList .= "<li class='file ext_".  $file->getExtension() . "'><a rel='" . $path . $file->getFilename() . "'>" . $file->getFilename() . "</a></li>";
                }
            }
            $resultList .= "</ul>";
        }


        return $resultList;
    }

}