<?php

namespace App\Libraries\MyCrawler\Mangboard;

use App\Libraries\MySocket\WebSocket;
use App\Entities\Mangboard\UserEntity;
use App\Libraries\MyCrawler\MyCrawler;
use App\Libraries\MyStorage\MangboardStorage;
use App\Models\Mangboard\BoardModel;
use App\Models\Mangboard\BoardsModel;

abstract class MangboardCrawler extends MyCrawler
{
    private $_mySocket = null;
    private $_host = "";
    protected $_board_name = "";
    private $_user_entity = null;
    protected function __construct(string $host, string $board_name, UserEntity $user_entity)
    {
        parent::__construct();
        $this->_host = $host;
        $this->_board_name = $board_name;
        $this->_user_entity = $user_entity;
    }
    abstract public function execute(int $max_limit): void;
    final protected function getMySocket()
    {
        if ($this->_mySocket === null) {
            $this->_mySocket = new WebSocket($this->_host);
        }
        return $this->_mySocket;
    }
    final protected function createMyStorage()
    {
        return new MangboardStorage($this->_board_name, $this->_user_entity);
    }
    protected function backend_process(int $cnt, array $listInfo, array $storages)
    {
        //File DB 및 Board DB 등록작업등
        $baord_name    = $this->_board_name;
        $boardsModel   = new BoardsModel();
        $boards_entity = $boardsModel->getEntityByID($this->_board_name);
        if ($boards_entity === null) {
            throw new \Exception(__FUNCTION__ . "=>{$this->_board_name}에 해당 Board 정보가 존재하지 않습니다.");
        }
        $boardModel    = new BoardModel("mb_" . $baord_name);
        $board_entity  = $boardModel->createByCrawler(
            $boards_entity,
            $this->_user_entity,
            $cnt,
            $listInfo,
            $storages
        );
        foreach ($storages as $storage) {
            try {
                $storage->backend($boards_entity, $board_entity, $boardModel->getTable());
            } 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()
                ));
            }
        }
    }
}
