<?php

namespace App\Libraries\Mangboard;

use App\Libraries\CommonLibrary;
use App\Models\Mangboard\BoardModel;
use App\Entities\Mangboard\UserEntity;
use App\Entities\Mangboard\BoardsEntity;
use App\Entities\Mangboard\BoardEntity;

class BoardLibrary extends CommonLibrary
{
    private $_model = null;
    private $_boards_entity = null;
    private $_user_entity = null;
    public function __construct(BoardsEntity $boards_entity, UserEntity $user_entity)
    {
        parent::__construct();
        $this->_boards_entity = $boards_entity;
        $this->_user_entity = $user_entity;
    }
    public function getModel(): BoardModel
    {
        if ($this->_model === null) {
            $table_name = "mb_" . $this->_boards_entity->getTitle();
            $this->_model = new BoardModel($table_name);
        }
        return $this->_model;
    }
    public function getBoardsEntity(): BoardsEntity
    {
        return $this->_boards_entity;
    }
    public function getUserEntity(): UserEntity
    {
        return $this->_user_entity;
    }

    public function createByCrawler(int $cnt, array $listInfo, array $storages): BoardEntity
    {
        $formDatas = [];
        //미디어관련정보 entity에 넣기
        $formDatas['title'] = $listInfo["title"];
        $formDatas['user_pid'] = $this->getUserEntity()->getPK();
        $formDatas['user_id'] = $this->getUserEntity()->getID();
        $formDatas['user_name'] = $listInfo["nickname"] != "" ? $listInfo["nickname"] : $this->getUserEntity()->getTitle();
        $formDatas['level'] = $this->getBoardsEntity()->getListLevel();
        $formDatas['hit'] = $listInfo['hit'];
        $formDatas['reg_date'] = date("Y-m-d H:i:s", strtotime($listInfo['date']));
        $formDatas['data_type'] = "html";
        $formDatas['editor_type'] = "S";
        $formDatas['image_path'] = "";
        $formDatas['content'] = "";
        foreach ($storages as $storage) {
            if ($formDatas['image_path'] == "") {
                $formDatas['image_path'] = sprintf("%s/%s/%s", $storage->getBasePath(), $storage->getPath(), $storage->getOriginName());
            }
            $formDatas['content'] .= $storage->getHTMLTag();
        }
        //망보드 게시판에 등록
        if ($formDatas['content'] == "") {
            throw new \Exception(sprintf(
                "%s=>%s번째 %s 내용이 없어 => %s 등록 취소",
                __FUNCTION__,
                $cnt,
                $listInfo["title"],
                $this->getModel()->getTable()
            ));
        }
        $entity = $this->getModel()->create($formDatas);
        log_message("notice", sprintf(
            "%s=>%s번째 %s => %s 등록 완료",
            __FUNCTION__,
            $cnt,
            $listInfo["title"],
            $this->getModel()->getTable()
        ));
        return $entity;
    }
}
