<?php

namespace App\Controllers\Admin\Equipment\Part;

use App\Helpers\Equipment\Part\DomainHelper;
use App\Services\Equipment\Part\DomainService;

use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class DomainController extends PartController
{
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->content_title      = lang("{$this->getService()->getClassName()}.title");
        $this->class_path .= $this->getService()->getClassName();
        $this->uri_path .= strtolower($this->getService()->getClassName('/')) . '/';
        // $this->view_path .= strtolower($this->getService()->getClassName()) . DIRECTORY_SEPARATOR;

    }
    public function getService(): DomainService
    {
        if (!$this->_service) {
            $this->_service = new DomainService();
        }
        return $this->_service;
    }
    public function getHelper(): DomainHelper
    {
        if (!$this->_helper) {
            $this->_helper = new DomainHelper();
        }
        return $this->_helper;
    }
    protected function getResultSuccess(string $message = MESSAGES["SUCCESS"], ?string $actionTemplate = null): RedirectResponse|string
    {
        helper(['form']);
        switch ($this->getAction()) {
            case 'create':
                $this->control = $this->getControlDatas();
                $this->getHelper()->setViewDatas($this->getViewDatas());
                $view_file = $this->view_path . 'domain' . DIRECTORY_SEPARATOR . 'view';
                $result = view($view_file, ['viewDatas' => $this->getViewDatas()]);
                break;
            case 'create_form':
                $result = parent::getResultSuccess($message, $this->request->getVar('ActionTemplate') ?? $actionTemplate ?? 'domain');
                break;
            default:
                $result = parent::getResultSuccess($message, $actionTemplate);
                break;
        }
        return $result;
    }
    //Index,FieldForm관련
    protected function create_process(array $formDatas): void
    {
        $entities = [];
        //formDatas는 Json 값으로 넘어온다.
        foreach (json_decode($formDatas['domain'], true) as $domain) {
            //데이터 검증
            $validDatas =  $this->doValidate(
                $this->getFieldRules(),
                ['domain' => $domain['value'], 'status' => $formDatas['status']]
            );
            $entities[] = $this->getService()->create($validDatas);
        }
        $this->entities = $entities;
    }
    //도메인 존재여부 검증용
    final public function confirm(string $field = "domain"): ResponseInterface
    {
        try {
            //각 Field 초기화:조건항목 Field는 한개만 존재하므로 Field와 Rule을 정의
            $this->setAction(__FUNCTION__);
            $this->setFormFields([$field]);
            $this->setFieldRule($field, $this->getFormFieldRule($this->getAction(), $field));
            //입력값정의
            $domain = $this->request->getVar($field);
            //기존 존재하는 Domain인지 확인용 Entity 가져오기
            $entity = $this->getService()->getEntity([$field => $domain], "");
            return $this->response
                ->setContentType('application/json')
                ->setBody(json_encode(['exists' => true, 'message' => "[{$entity->getTitle()}] 이미 존재하는 도메인입니다."]));
        } catch (\Exception $e) {
            return $this->response
                ->setContentType('application/json')
                ->setBody(json_encode(['exists' => false, 'message' => $e->getMessage()]));
        }
    }
}
