<?php

namespace App\Libraries\MyStorage;

use App\Traits\FileTrait;

class FileStorage extends MyStorage
{
    use FileTrait;
    private $_path = "";
    private $_mimeType = "";
    private $_fileSize = 0;
    private $_fileSequence = 0;
    private $_imageLibrary = null;
    public function __construct(string $path)
    {
        parent::__construct();
        $this->_path = $path;
    }
    final public function getPath(): string
    {
        return $this->_path;
    }
    public function getUploadPath(): string
    {
        return "uploads";
    }
    final public function getFullPath(): string
    {
        $full_path = WRITEPATH . $this->getUploadPath() . DIRECTORY_SEPARATOR . $this->getPath();
        $this->mkdir_FileTrait($full_path);
        return $full_path;
    }
    public function getUploadURL(): string
    {
        return "uploads";
    }

    final public function getMimeType(): string
    {
        return $this->_mimeType;
    }
    final public function getFileSize(): int
    {
        return $this->_fileSize;
    }
    final public function getFileSequence(): int
    {
        return $this->_fileSequence;
    }

    public function save(): static
    {
        // log_message("notice", __FUNCTION__ . " 원본파일 {$this->getOriginName()} 작업 시작 2");
        $save_file = $this->getFullPath() . DIRECTORY_SEPARATOR . $this->getOriginName();
        log_message("debug", __FUNCTION__ . " {$save_file} 작업 시작");
        //중복된 파일명인지 확인후 새로운 이름으로 저장
        if (file_exists($save_file)) {
            switch (getenv("mangboard.uploads.file.collision")) {
                case "unique":
                    $file_name = $this->getUniqueName_FileTrait($this->getFullPath(), $this->getOriginName());
                    log_message("notice", __FUNCTION__ . " 파일명 변경 : 원본파일 {$this->getOriginName()}->저장파일 {$file_name}");
                    $this->setOriginName($file_name);
                    $save_file = $this->getFullPath() . DIRECTORY_SEPARATOR . $this->getOriginName();
                    break;
                case "notallow":
                default:
                    throw new \Exception(__FUNCTION__ . " {$this->getOriginName()} 는 이미 존재하는 파일입니다.");
                    // break;
            }
        }
        //원본이미지 저장
        if (!file_put_contents($save_file, $this->getOriginContent())) {
            throw new \Exception(__FUNCTION__ . " 파일저장 실패:{$save_file}");
        }
        $this->_mimeType = mime_content_type($save_file);
        $this->_fileSize = filesize($save_file);
        log_message("notice", __FUNCTION__ . " 원본파일 {$this->getOriginName()} 작업 완료");
        return $this;
    }
}
