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

namespace Balbooa\Component\Forms\Site\Helper\Uploads\Contracts;

use Balbooa\Component\Forms\Administrator\Helper\Filesystem\File;
use Balbooa\Component\Forms\Administrator\Helper\Filesystem\Folder;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Uri\Uri;

defined('_JEXEC') or die;

abstract class AbstractUploads implements UploadsInterface
{
    protected string $storagePath;

    public function __construct()
    {
        $params = ComponentHelper::getParams('com_baforms');
        $this->storagePath = $params->get($this->getOptionKey(), $this->getOptionDefaultValue());
    }

    abstract protected function getOptionKey(): string;
    abstract protected function getOptionDefaultValue(): string;

    protected function isDefaultFolder(): bool
    {
        return $this->storagePath === $this->getOptionDefaultValue();
    }

    public function generateFilename(int $formId, string $ext): ?string
    {
        $dir = JPATH_ROOT . '/' . $this->storagePath;
        if ($this->isDefaultFolder() && !Folder::exists($dir)) {
            Folder::create($dir);
        }

        if (!Folder::exists($dir)) {
            return null;
        }

        $dir .= "/form-$formId/";
        if (!Folder::exists($dir)) {
            Folder::create($dir);
        }

        $name = File::generateSafeName($dir, $ext);

        return "$name.$ext";
    }

    public function getStorageFilePath(int $formId, string $filename): string
    {
        return "$this->storagePath/form-$formId/$filename";
    }

    public function getFilePath(int $formId, string $filename): string
    {
        $path = $this->getStorageFilePath($formId, $filename);

        return JPATH_ROOT . "/$path";
    }

    public function getFileLink(int $formId, string $filename): string
    {
        return Uri::root() . $this->getStorageFilePath($formId, $filename);
    }

    public function getStoragePath(): string
    {
        return $this->storagePath;
    }
}