<?php

namespace App\Services\Equipment;

use App\Entities\Equipment\ServerEntity;
use App\Entities\Equipment\ServerPartEntity;
use App\Entities\PaymentEntity;
use App\Helpers\Equipment\ServerPartHelper;
use App\Models\Equipment\ServerPartModel;
use App\Services\Equipment\EquipmentService;
use App\Services\Equipment\ServerPart\ServiceService;
use App\Services\Equipment\ServerPart\ServerService;
use App\Services\Equipment\ServerPart\CSService;
use App\Services\Equipment\ServerPart\IPService;
use App\Services\Equipment\ServerPart\PartService;
use App\Services\Equipment\ServerPart\SwitchService;
use App\Services\Equipment\ServerPart\PaymentService;

class ServerPartService extends EquipmentService
{
    private ?ServiceService $_serviceService = null;
    private ?ServerService $_serverService = null;
    private ?SwitchService $_switchService = null;
    private ?PartService $_partService = null;
    private ?IPService $_ipService = null;
    private ?CSService $_csService = null;
    private ?PaymentService $_paymentService = null;
    public function __construct()
    {
        parent::__construct(new ServerPartModel(), new ServerPartHelper());
        $this->addClassName('ServerPart');
    }
    public function getFormFields(): array
    {
        return [
            "serverinfo_uid",
            "type",
            "billing",
            "part_uid",
            "title",
            "cnt",
            "extra",
            "amount",
        ];
    }
    public function getFormFilters(): array
    {
        return [
            "serverinfo_uid",
            "type",
            "part_uid",
            "billing",
        ];
    }

    public function getIndexFields(): array
    {
        return [
            "serverinfo_uid",
            "type",
            "part_uid",
            "billing",
            "amount",
            "cnt",
            "extra",
        ];
    }
    public function getIndexFilters(): array
    {
        return [
            "serverinfo_uid",
            "type",
            "part_uid",
            "billing",
        ];
    }
    public function getBatchjobFields(): array
    {
        return ['billing', 'type'];
    }
    final public function getServiceService(): ServiceService
    {
        if (!$this->_serviceService) {
            $this->_serviceService = new ServiceService();
        }
        return $this->_serviceService;
    }
    final public function getServerService(): ServerService
    {
        if (!$this->_serverService) {
            $this->_serverService = new ServerService();
        }
        return $this->_serverService;
    }
    final public function getPartService(): PartService
    {
        if (!$this->_partService) {
            $this->_partService = new PartService();
        }
        return $this->_partService;
    }
    final public function getSwitchService(): SwitchService
    {
        if (!$this->_switchService) {
            $this->_switchService = new SwitchService();
        }
        return $this->_switchService;
    }
    final public function getIPService(): IPService
    {
        if (!$this->_ipService) {
            $this->_ipService = new IPService();
        }
        return $this->_ipService;
    }
    final public function getCSService(): CSService
    {
        if (!$this->_csService) {
            $this->_csService = new CSService();
        }
        return $this->_csService;
    }
    final public function getPaymentService(): PaymentService
    {
        if (!$this->_paymentService) {
            $this->_paymentService = new PaymentService();
        }
        return $this->_paymentService;
    }
    //partEntity 정보 추가
    protected function getEntity_process(mixed $entity): ServerPartEntity
    {
        if (!$entity instanceof ServerPartEntity) {
            throw new \Exception(__METHOD__ . "에서 형식오류:ServicePartEntity만 허용됩니다.");
        }
        switch ($entity->getType()) {
            case 'CPU':
            case 'RAM':
            case 'DISK':
            case 'OS':
            case 'DB':
            case 'SOFTWARE':
                $entity->setPartEntity($this->getPartService()->getEntity($entity->getPartUID()));
                break;
            case 'SWITCH':
                $entity->setPartEntity($this->getSwitchService()->getEntity($entity->getPartUID()));
                break;
            case 'IP':
                $entity->setPartEntity($this->getIPService()->getEntity($entity->getPartUID()));
                break;
            case 'CS':
                $entity->setPartEntity($this->getCSService()->getEntity($entity->getPartUID()));
                break;
        }
        //결제정보 정의
        if ($entity->getPaymentUID()) {
            $paymentEntity = $this->getPaymentService()->getEntity($entity->getPaymentUID());
            if ($paymentEntity instanceof PaymentEntity) {
                $entity->setPaymentEntity($paymentEntity);
            }
        }
        return $entity;
    }
    //기본 기능부분
    // FieldForm관련용
    public function getFormOption(string $field, array $options = []): array
    {
        switch ($field) {
            case 'part_uid':
                $partOptions = [];
                foreach (SERVERPART['ALL_PARTTYPES'] as $partType) {
                    switch ($partType) {
                        case 'CPU':
                        case 'RAM':
                        case 'DISK':
                        case 'OS':
                        case 'DB':
                        case 'SOFTWARE':
                            $partOptions[$partType] = $this->getPartService()->getEntities(['type' => $partType]);
                            break;
                        case 'SWITCH':
                            $partOptions[$partType] = $this->getSwitchService()->getEntities();
                            break;
                        case 'IP':
                            $partOptions[$partType] = $this->getIPService()->getEntities();
                            break;
                        case 'CS':
                            $partOptions[$partType] = $this->getCSService()->getEntities();
                            break;
                        default:
                            $partOptions[$partType] = [];
                            break;
                    }
                }
                $options = $partOptions;
                // dd($options);
                break;
            default:
                $options = parent::getFormOption($field, $options);
                break;
        }
        if (!is_array($options)) {
            throw new \Exception(__FUNCTION__ . "에서 {$field}의 options 값이 array가 아닙니다.\n" . var_export($options, true));
        }
        return $options;
    }
    //파트별정보 설정
    private function action_process(ServerPartEntity $entity, string $action): ServerPartEntity
    {
        //Type에 따른 부품서비스 정의
        switch ($entity->getType()) {
            case 'CPU':
            case 'RAM':
            case 'DISK':
            case 'OS':
            case 'DB':
            case 'SOFTWARE':
                $entity = $this->getPartService()->$action($entity);
                break;
            case 'SWITCH':
                $entity = $this->getSwitchService()->$action($entity);
                break;
            case 'IP':
                $entity = $this->getIPService()->$action($entity);
                break;
            case 'CS':
                $entity = $this->getCSService()->$action($entity);
                break;
        }
        //서비스 및 결제정보 처리
        switch ($entity->getBilling()) {
            case PAYMENT['BILLING']['MONTH']: //월별
                $entity = $this->getServiceService()->$action($entity);
                break;
            case PAYMENT['BILLING']['ONETIME']: //일회성
                $entity = $this->getPaymentService()->$action($entity);
                break;
            case PAYMENT['BILLING']['BASE']: //기본
                //아무처리 않함
                break;
            default:
                throw new \Exception(__METHOD__ . "에서 오류발생:{$entity->getBilling()}은 지정되지 않은 결제방식입니다.");
                // break;
        }
        return $entity;
    }
    //부품연결정보생성
    public function create(array $formDatas): ServerPartEntity
    {
        //서버정보가져오기
        $serverEntity = null;
        if (array_key_exists('serverEntity', $formDatas)) {
            $serverEntity = $formDatas['serverEntity'];
        } else {
            if (!array_key_exists('serverinfo_uid', $formDatas)) {
                throw new \Exception("서버 정보가 지정되지 않았습니다.");
            }
            $serverEntity = $this->getServerService()->getEntity($formDatas['serverinfo_uid']);
        }
        if (!$serverEntity instanceof ServerEntity) {
            throw new \Exception("서버 정보가 지정되지 않았습니다.");
        }
        //생성작업
        $formDatas["clientinfo_uid"]  = $serverEntity->getClientInfoUID();
        $formDatas["serviceinfo_uid"]  = $serverEntity->getServiceInfoUID();
        $formDatas["serverinfo_uid"] = $serverEntity->getPK();
        $entity = parent::create($formDatas);
        //부품연결정보관련 정보처리
        return  $this->action_process($entity, __FUNCTION__ . 'ServerPart');
    }
    //수정
    public function modify(mixed $entity, array $formDatas): ServerPartEntity
    {
        //서버정보가져오기
        if (!array_key_exists('serverinfo_uid', $formDatas)) {
            throw new \Exception("서버 정보가 지정되지 않았습니다.");
        }
        $serverEntity = $this->getServerService()->getEntity($formDatas['serverinfo_uid']);
        if (!$serverEntity instanceof ServerEntity) {
            throw new \Exception("서버 정보가 지정되지 않았습니다.");
        }
        //수정 전 부품연결정보관련 정보처리
        if ($entity->getCnt() != $formDatas['cnt'] ||  $entity->getPartUID() !== $formDatas['part_uid']) {
            $entity = $this->action_process($entity,   'deleteServerPart');
        }
        //수정작업
        $formDatas["clientinfo_uid"]  = $serverEntity->getClientInfoUID();
        $formDatas["serviceinfo_uid"]  = $serverEntity->getServiceInfoUID();
        $formDatas["serverinfo_uid"] = $serverEntity->getPK();
        $entity = parent::modify($entity, $formDatas);
        //수정 후 부품연결정보관련 정보처리
        $entity = $this->action_process($entity, __FUNCTION__ . 'ServerPart');
        return $entity;
    }
    //삭제
    public function delete(mixed $entity): ServerPartEntity
    {
        //부품연결정보관련 정보처리
        $entity = $this->action_process($entity, __FUNCTION__ . 'ServerPart');
        return parent::delete($entity);
    }
}
