<?php

namespace App\Services\Equipment;

use App\Entities\Equipment\ServerEntity;
use App\Entities\Equipment\ServerPartEntity;
use App\Helpers\Equipment\ServerPartHelper;
use App\Models\Equipment\ServerPartModel;
use App\Services\Equipment\EquipmentService;

class ServerPartService extends EquipmentService
{
    private ?SwitchService $_switchService = null;
    private ?PartService $_partService = null;
    private ?IPService $_ipService = null;
    private ?CSService $_csService = null;
    public function __construct()
    {
        parent::__construct(new ServerPartModel(), new ServerPartHelper());
        $this->addClassName('ServerPart');
    }
    public function getFormFields(): array
    {
        return [
            "serverinfo_uid",
            "type",
            "part_uid",
            "billing",
            "amount",
            "cnt",
            "extra",
        ];
    }
    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 getSwitchService(): SwitchService
    {
        if (!$this->_switchService) {
            $this->_switchService = new SwitchService();
        }
        return $this->_switchService;
    }
    final public function getPartService(): PartService
    {
        if (!$this->_partService) {
            $this->_partService = new PartService();
        }
        return $this->_partService;
    }
    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;
    }
    //partEntity 정보 추가
    protected function getEntity_process(mixed $entity): ServerPartEntity
    {
        if (!($entity instanceof ServerPartEntity)) {
            throw new \Exception(__METHOD__ . "에서 형식오류:ServicePartEntity만 허용됩니다.");
        }
        switch ($entity->getType()) {
            case 'SWITCH':
                $partService = $this->getSwitchService();
                break;
            case 'IP':
                $partService = $this->getIPService();
                break;
            case 'CS':
                $partService = $this->getCSService();
                break;
            default:
                $partService = $this->getPartService();
                break;
        }
        return $entity->setPartEntity($partService->getEntity($entity->getPartUID()));
    }
    //기본 기능부분
    // FieldForm관련용
    public function getFormOption(string $field, array $options = []): array
    {
        switch ($field) {
            case 'part_uid':
                $type = $this->getFormDatas()['type'] ?? null;
                switch ($type) {
                    case 'CPU':
                    case 'RAM':
                    case 'DISK':
                    case 'OS':
                    case 'DB':
                    case 'SOFTWARE':
                        $options = $this->getPartService()->getEntities(['type' => $type]);
                        break;
                    case 'SWITCH':
                        $options = $this->getSwitchService()->getEntities();
                        break;
                    case 'IP':
                        $options = $this->getIPService()->getEntities();
                        break;
                    case 'CS':
                        $options = $this->getCSService()->getEntities();
                        break;
                    default:
                        $options = [];
                        break;
                }
                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 setPart_process(ServerPartEntity $entity, mixed $part_uid, string $status): mixed
    {
        //Type에 따른 부품서비스 정의
        switch ($entity->getType()) {
            case 'SWITCH':
                $partService = $this->getSwitchService();
                break;
            case 'IP':
                $partService = $this->getIPService();
                break;
            case 'CS':
                $partService = $this->getCSService();
                break;
            default:
                $partService = $this->getPartService();
                break;
        }
        //부품정보가져오기
        $partEntity = $partService->getEntity($part_uid);
        if (!$partEntity) {
            throw new \Exception(__METHOD__ . "에서 오류:{$part_uid}에 해닫하는 {$entity->getType()}정보가 없습니다.");
        }
        $formDatas = [];
        switch ($entity->getType()) {
            case 'IP':
                //기존IP 사용자로 고객정보 설정
                $formDatas['old_clientinfo_uid'] = $partEntity->getClientInfoUID();
            case 'SWITCH':
            case 'CS':
                //부품정보에 서버정보 설정 및 서비스,고객정보 정의
                if ($status === STATUS['AVAILABLE']) {
                    //사용가능
                    $formDatas['clientinfo_uid']  = null;
                    $formDatas['serviceinfo_uid'] = null;
                    $formDatas['serverinfo_uid']  = null;
                } else {
                    $formDatas['clientinfo_uid']  = $entity->getClientInfoUID();
                    $formDatas['serviceinfo_uid'] = $entity->getServiceInfoUID();
                    $formDatas['serverinfo_uid']  = $entity->getServerInfoUID();
                }
                $formDatas['part_uid'] = $part_uid;
                $formDatas['status']  = $status;
                $partEntity = $partService->modify($partEntity, $formDatas);
                break;
        }
        return $partEntity;
    }
    //부품연결정보생성
    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 $entity->setPartEntity($this->setPart_process(
            $entity,
            $formDatas['part_uid'],
            STATUS['OCCUPIED']
        ));
    }
    //수정
    public function modify(mixed $entity, 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();
        //기존 Part_UID와 신규 Part_UID가 다르면 기존 Part정보 사용가능으로 변경
        if ($entity->getPartUID() != $formDatas['part_uid']) {
            $this->setPart_process($entity, $entity->getPartUID(),  STATUS['AVAILABLE']);
        }
        //기존 정보변경
        $entity = parent::modify($entity, $formDatas);
        //부품연결정보에 부품정보 정의
        return $entity->setPartEntity($this->setPart_process(
            $entity,
            $formDatas['part_uid'],
            STATUS['OCCUPIED']
        ));
    }
    //삭제
    public function delete(mixed $entity): ServerPartEntity
    {
        $this->setPart_process($entity, $entity->getPartUID(),  STATUS['AVAILABLE']);
        return parent::delete($entity);
    }
}
