<?php

namespace App\Controllers\Admin\Customer;


use App\Entities\Customer\ServiceEntity;
use App\Entities\Customer\ServiceItemEntity;
use App\Helpers\Customer\ServiceItemHelper;
use App\Services\Customer\ServiceItemService;

use App\Services\Customer\ServiceService;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class ServiceItemController extends CustomerController
{
    private ?ServiceService $_serviceService = null;
    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;

    }
    protected function initAction(string $action): void
    {
        parent::initAction($action);
        //LINE,IP,SERVER등 추가 FilterOption 셋팅용
        foreach (SERVICE_ITEM_TYPES as $item_type => $label) {
            $options = $this->getService()->getServiceItemLinkService($item_type)->getEntities();
            $this->setFieldRule($item_type, $this->getFormFieldRule($this->getAction(), $item_type));
            $this->setFilterFieldOption($item_type, $options);
        }
    }
    public function getService(): ServiceItemService
    {
        if (!$this->_service) {
            $this->_service = new ServiceItemService($this->request);
        }
        return $this->_service;
    }
    public function getHelper(): ServiceItemHelper
    {
        if (!$this->_helper) {
            $this->_helper = new ServiceItemHelper($this->request);
        }
        return $this->_helper;
    }
    public function getServiceService(): ServiceService
    {
        if (!$this->_serviceService) {
            $this->_serviceService = new ServiceService($this->request);
        }
        return $this->_serviceService;
    }
    protected function getResultSuccess(string $message = MESSAGES["SUCCESS"], ?string $actionTemplate = null): RedirectResponse|string
    {
        switch ($this->getAction()) {
            case 'create_form':
            case 'modify_form':
            case 'index':
                $result = parent::getResultSuccess($message, $this->request->getVar('ActionTemplate') ?? $actionTemplate ?? 'popup');
                break;
            default:
                $result = parent::getResultSuccess($message, $actionTemplate);
                break;
        }
        return $result;
    }
    public function getFormFieldOption(string $field, array $options = []): array
    {
        switch ($field) {
            case 'item_uid':
                $item_type = $this->request->getVar('item_type');
                if (!$item_type) {
                    throw new \Exception(__FUNCTION__ . "에서 item_type이 지정되지 않았습니다.");
                }
                //$item_type(CPU,RAM,STORAGE등)에 따라 선언된 getFormFieldOption사용 됨
                $options = $this->getFilterFieldOption($item_type);
                break;
            default:
                $options = parent::getFormFieldOption($field, $options);
                break;
        }
        return $options;
    }
    //Index,FieldForm관련

    //item_type에 따른 item_uid 값 가져오기
    private function setItemUID(ServiceEntity $serviceEntity, array $formDatas): array
    {
        switch ($formDatas['item_type']) {
            case 'DOMAIN':
                //DomainService에 먼저 create후 결과 uid를 item_uid로 전달함
                $equipmentEntity = $this->getService()->getServiceItemLinkService($formDatas['item_type'])->create([
                    'clientinfo_uid' => $serviceEntity->getClientUID(),
                    'domain' => $formDatas['item_uid']
                ]);
                //도메인용 항목의 item_uid로 전달함
                $formDatas['item_uid'] = $equipmentEntity->getPK();
                break;
        }
        return $formDatas;
    }
    protected function create_process(array $formDatas): ServiceItemEntity
    {
        $serviceEntity = $this->getServiceService()->getEntity($formDatas['serviceinfo_uid']);
        if (!$serviceEntity) {
            throw new \Exception("{$formDatas['serviceinfo_uid']}에 대한 서비스정보를 찾을수 없습니다.");
        }
        //item_type에 따른 item_uid 값 가져오기 반드시 Validation 전에 정의해야함
        $formDatas = $this->setItemUID($serviceEntity, $formDatas);
        return parent::create_process($formDatas);
    }
}
