<?php

namespace App\Libraries\MyStorage;

use App\Entities\Mangboard\BoardEntity;
use App\Entities\Mangboard\BoardsEntity;
use App\Entities\Mangboard\UserEntity;
use App\Models\Mangboard\FileModel;
use App\Traits\ImageTrait;

class MangboardStorage extends FileStorage
{
    use ImageTrait;
    private $_board_name = "";
    private $_user_entity = null;
    private $_fileModel = null;
    public function __construct(string $board_name, UserEntity $user_entity)
    {
        parent::__construct($board_name);
        $this->_board_name    = $board_name;
        $this->_user_entity = $user_entity;
    }
    final protected function getFileModel(): FileModel
    {
        if ($this->_fileModel === null) {
            $this->_fileModel = new FileModel();
        }
        return $this->_fileModel;
    }
    final public function getBasePath(): string
    {
        return getenv("mangboard.uploads.path");
    }
    final public function getUploadPath(): string
    {
        return parent::getUploadPath() . DIRECTORY_SEPARATOR . $this->getBasePath();
    }
    final public function getUploadURL(): string
    {
        return sprintf("/wp-content/%s/%s/%s", parent::getUploadURL(), $this->getBasePath(), $this->getBasePath());
    }
    final public function getHTMLTag(string $content = ""): string
    {
        //Board 게시판 image_path , content용 데이터 배열에 추가 후 modifyBoard에서 처리
        switch ($this->getOrintginType()) {
            case "image":
                $content = sprintf(
                    "<img src=\"%s/%s/%s\" alt=\"%s\">",
                    $this->getUploadURL(),
                    $this->getPath(),
                    $this->getOriginName(),
                    $this->getOriginName()
                );
                break;
            case "video":
                $content = sprintf(
                    "<video alt=\"%s\" controls autoplay>
                        <source src=\"%s/%s/%s\" type=\"%s\">
                        Your browser does not support the video tag.
                    </video>",
                    $this->getOriginName(),
                    $this->getUploadURL(),
                    $this->getPath(),
                    $this->getOriginName(),
                    $this->getMimeType(),
                );
                break;
        }
        log_message("debug", sprintf(
            "\n--------%s--------\n%s\n--------------------\n",
            __FUNCTION__,
            $content
        ));
        return $content;
    }

    final public function backend(BoardsEntity $boards_entity, BoardEntity $board_entity, string $board_table)
    {
        $this->getFileModel()->createByCrawler(
            $boards_entity,
            $this->_user_entity,
            $board_entity,
            $board_table,
            $this
        );
        $this->create_small_ImageTrait($board_entity, $this);
    }
}
