<?php

namespace App\Libraries\Mangboard;

use App\Traits\ImageTrait;
use App\Traits\FileTrait;
use App\Libraries\MyStorage\MangboardStorage;
use App\Libraries\CommonLibrary;
use App\Entities\Mangboard\BoardEntity;

class ImageLibrary extends CommonLibrary
{
    use FileTrait, ImageTrait;
    public function __construct()
    {
        parent::__construct();
    }
    public function create(MangboardStorage $storage, $target = "small", int $width = 480, int $height = 319): string
    {
        $fileInfo = pathinfo($storage->getFullPath() . DIRECTORY_SEPARATOR . $storage->getOriginName(), PATHINFO_ALL);
        $target_file_name = sprintf("%s_%s.%s", $fileInfo['filename'], $target, $fileInfo['extension']);

        if (!$this->isFileType_FileTrait($fileInfo['extension'])) {
            throw new \Exception("{$storage->getOriginName()} Image 형식파일이 아닙니다.");
        }
        // 이미지 파일 로드
        $this->load_ImageTrait($storage->getFullPath() . DIRECTORY_SEPARATOR . $storage->getOriginName());
        // 200x200으로 이미지 크기 조정
        $this->resize_ImageTrait($width, $height);
        // 파일 저장
        $this->save_ImageTrait($storage->getFullPath() . DIRECTORY_SEPARATOR . $target_file_name);
        // 메모리 해제
        $this->destroy_ImageTrait();
        log_message("debug", sprintf(
            "%s %s->%s(W:%s,H:%s) 작업완료)",
            __FUNCTION__,
            $storage->getOriginName(),
            $target_file_name,
            $width,
            $height
        ));
        return $target_file_name;
    }
    public function createByCrawler(BoardEntity $board_entity, array $storages): void
    {
        try {
            foreach ($storages as $storage) {
                $file_name = $this->create($storage);
                log_message("notice", sprintf(
                    "%s -> %s 게시물의 %s번째:%s 작은이미지 생성 완료",
                    __FUNCTION__,
                    $board_entity->getTitle(),
                    $storage->getOriginSequence(),
                    $file_name
                ));
            }
        } catch (\Exception $e) {
            log_message("notice", sprintf(
                "\n---%s -> %s 게시물의 %s번째:%s 작은이미지 생성 오류---\n%s\n--------------------------------\n",
                __FUNCTION__,
                $board_entity->getTitle(),
                $storage->getOriginSequence(),
                $storage->getOriginName(),
                $e->getMessage()
            ));
        }
    }
}
