<?php

namespace App\Services;

use RuntimeException;
use App\Models\BoardModel;
use App\Helpers\BoardHelper;
use App\Forms\BoardForm;
use App\Entities\CommonEntity;
use App\Entities\BoardEntity;
use App\DTOs\BoardDTO;

class BoardService extends CommonService
{
    private $_form = null;
    private $_helper = null;
    public function __construct(BoardModel $model)
    {
        parent::__construct($model);
        $this->addClassPaths('Board');
    }
    protected function getDTOClass(): string
    {
        return BOARDDTO::class;
    }
    public function createDTO(array $formDatas): BoardDTO
    {
        return new BoardDTO($formDatas);
    }
    public function getEntityClass(): string
    {
        return BoardEntity::class;
    }
    public function getFormService(): BoardForm
    {
        if ($this->_form === null) {
            $this->_form = new BoardForm();
            $this->_form->setAttributes([
                'pk_field'         => $this->model->getPKField(),
                'title_field'      => $this->model->getTitleField(),
                'table'            => $this->model->getTable(),
                'useAutoIncrement' => $this->model->useAutoIncrement(),
                'class_path' => $this->getClassPaths(false)
            ]);
        }
        return $this->_form;
    }
    public function getHelper(): BoardHelper
    {
        if ($this->_helper === null) {
            $this->_helper = new BoardHelper();
            $this->_helper->setAttributes([
                'pk_field'         => $this->model->getPKField(),
                'title_field'      => $this->model->getTitleField(),
                'table'            => $this->model->getTable(),
                'useAutoIncrement' => $this->model->useAutoIncrement(),
                'class_path' => $this->getClassPaths(false)
            ]);
        }
        return $this->_helper;
    }
    public function action_init_process(string $action, array $formDatas = []): void
    {
        $fields          = [
            'category',
            'worker_uid',
            'title',
            'status',
            'content',
        ];
        $filters         = [
            'user_uid',
            'worker_uid',
            'category',
            'status',
        ];
        $indexFilter     = $filters;
        $batchjobFilters = ['user_uid', 'category', 'status'];
        switch ($action) {
            case 'create':
            case 'create_form':
                break;
            case 'modify':
            case 'modify_form':
                $fields = [...$fields, 'status'];
                break;
            case 'view':
                $fields = [
                    'category',
                    'worker_uid',
                    'title',
                    'status',
                    'created_at',
                    'content'
                ];
                break;
            case 'index':
                $fields = [
                    'category',
                    'worker_uid',
                    'title',
                    'status',
                    'created_at'
                ];
                break;
            case 'download':
                $fields = [
                    'category',
                    'worker_uid',
                    'title',
                    'status',
                    'created_at',
                    'content'
                ];
                break;
        }
        $this->getFormService()->setFormFields($fields);
        $this->getFormService()->setFormRules($action, $fields);
        $this->getFormService()->setFormFilters($filters);
        $this->getFormService()->setFormOptions($action, $filters, $formDatas);
        $this->getFormService()->setIndexFilters($indexFilter);
        $this->getFormService()->setBatchjobFilters($batchjobFilters);
    }
    //기본 기능부분
    protected function getEntity_process(mixed $entity): BoardEntity
    {
        return $entity;
    }
    protected function create_process(array $formDatas): BoardEntity
    {
        return parent::create_process($formDatas);
    }
    protected function modify_process($entity, array $formDatas): BoardEntity
    {
        return parent::modify_process($entity, $formDatas);
    }
    //List 검색용
    //FormFilter 조건절 처리
    //검색어조건절처리

    //추가기능부분
    //Category별 최근 $limit갯수만큼 게시물
    public function getLatest(string $category): array
    {
        //관리자정보
        $userEntities = service('userservice')->getEntities();
        $datas     = [];
        foreach ($this->getEntities(['category' => $category, 'status' => STATUS['AVAILABLE']]) as $entity) {
            $datas[] = [
                'title' => "<label for=\"view\" data-src=\"/admin/board/view/{$entity->getPK()}\" data-bs-toggle=\"modal\" data-bs-target=\" #modal_action_form\" class=\"text-primary form-label-sm\">{$entity->getTitle()}</label>",
                'created_at' => date('Y-m-d H:m', strtotime($entity->getCreatedAT())),
                'user' => $userEntities[$entity->getUserUID()]->getTitle(),
            ];
        }
        return $datas;
    }
    //요청업무 갯수(Home에서 사용)
    public function getRequestTaskCount(int $worker_uid): int
    {
        return count($this->getEntities([
            'category' => BOARD['CATEGORY']['REQUESTTASK'],
            'worker_uid' => $worker_uid,
            'status' => STATUS['AVAILABLE']
        ]));
    }
}
