<?php
/**
* @package   Gridbox
* @author    Balbooa http://www.balbooa.com/
* @copyright Copyright @ Balbooa
* @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
*/

namespace Balbooa\Component\Gridbox\Site\Helper\Dashboard;

use Balbooa\Component\Gridbox\Administrator\Helper\Filesystem\File;
use Balbooa\Component\Gridbox\Administrator\Helper\Filesystem\Folder;
use Joomla\CMS\Uri\Uri;
use Balbooa\Component\Gridbox\Site\Helper\FileHelper;
use Balbooa\Component\Gridbox\Site\Interface\DashboardInterface;
use Balbooa\Component\Gridbox\Site\Interface\DashboardItemsInterface;

class FilesHelper implements DashboardInterface, DashboardItemsInterface
{
    private $filePath;
    private $fileUrl;

    public static function make() :static
    {
        return new static();
    }
    
    public function getItems($directory = '/'):array
    {
        if (empty($this->filePath)) {
            $this->filePath = JPATH_ROOT . '/'. FileHelper::getImagePath();
            $this->fileUrl = Uri::root() . FileHelper::getImagePath();
        }
        $dir = $this->filePath . $directory;
        $url = $this->fileUrl . $directory;
        $files = Folder::files($dir);
        $items = [];
        $types = FileHelper::getTypes();
        foreach ($files as $file) {
            $ext = strtolower(File::getExt($file));
            if (!in_array($ext, $types)) {
                continue;
            }
            $modify = filemtime($dir . $file);
            $items[] = (object)[
                'ext' => $ext,
                'title' => $file,
                'url' => $url . $file,
                'size' => FileHelper::getFileSize(filesize($dir . $file)),
                'path' => $directory . $file,
                'modify' => $modify,
                'date' => date('Y-m-d-H-i-s', $modify),
            ];
        }
        $folders = Folder::folders($dir);
        foreach ($folders as $folder) {
            if ($folder != 'attachment' && $folder != 'bagallery' && $folder != 'baforms') {
                $array = $this->getItems($directory . $folder . '/');
                $items = array_merge($items, $array);
            }
        }
        usort($items, function($a, $b){
            if ($a->modify == $b->modify) {
                return 0;
            }
            return ($a->modify < $b->modify) ? 1 : -1;
        });

        return array_slice($items, 0, 10);
    }
}