<?php

namespace App\Services\Equipment;

use App\Entities\Equipment\ServerEntity;
use App\Entities\Equipment\ServerPartEntity;
use App\Entities\Part\PartEntity;
use App\Helpers\Equipment\ServerPartHelper;
use App\Models\Equipment\ServerPartModel;
use App\Processors\Equipment\ServerPartV1Processor as Proceessor;
use App\Services\Customer\ServiceService;
use App\Services\Equipment\EquipmentService;
use App\Services\Equipment\ServerService;
use App\Services\Part\CPUService;
use App\Services\Part\CSService;
use App\Services\Part\DISKService;
use App\Services\Part\IPService;
use App\Services\Part\RAMService;
use App\Services\Part\SOFTWAREService;
use App\Services\Part\SWITCHService;
use App\Services\PaymentService;

class ServerPartService extends EquipmentService
{
    private ?ServiceService $_serviceService = null;
    private ?ServerService $_serverService = null;
    private ?PaymentService $_paymentService = null;
    private ?CPUService $_cpuService = null;
    private ?RAMService $_ramService = null;
    private ?DISKService $_diskService = null;
    private ?SOFTWAREService $_softwareService = null;
    private ?SWITCHService $_switchService = null;
    private ?IPService $_ipService = null;
    private ?CSService $_csService = null;

    private $_partServices = [];
    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",
            "title",
            "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 getPaymentService(): PaymentService
    {
        if (!$this->_paymentService) {
            $this->_paymentService = new PaymentService();
        }
        return $this->_paymentService;
    }
    final public function getCPUService(): CPUService
    {
        if (!$this->_cpuService) {
            $this->_cpuService = new CPUService();
        }
        return $this->_cpuService;
    }
    final public function getRAMService(): RAMService
    {
        if (!$this->_ramService) {
            $this->_ramService = new RAMService();
        }
        return $this->_ramService;
    }
    final public function getDISKService(): DISKService
    {
        if (!$this->_diskService) {
            $this->_diskService = new DISKService();
        }
        return $this->_diskService;
    }
    final public function getSOFTWAREService(): SOFTWAREService
    {
        if (!$this->_softwareService) {
            $this->_softwareService = new SOFTWAREService();
        }
        return $this->_softwareService;
    }
    final public function getCSService(): CSService
    {
        if (!$this->_csService) {
            $this->_csService = new CSService();
        }
        return $this->_csService;
    }

    final public function getIPService(): IPService
    {
        if (!$this->_ipService) {
            $this->_ipService = new IPService();
        }
        return $this->_ipService;
    }

    final public function getSWITCHService(): SWITCHService
    {
        if (!$this->_switchService) {
            $this->_switchService = new SWITCHService();
        }
        return $this->_switchService;
    }
    final public function getPartService(string $type)
    {
        switch ($type) {
            case 'CPU':
                $service = $this->getCPUService();
                break;
            case 'RAM':
                $service = $this->getRAMService();
                break;
            case 'DISK':
                $service = $this->getDISKService();
                break;
            case 'SOFTWARE':
                $service = $this->getSOFTWAREService();
                break;
            case 'IP':
                $service = $this->getIPService();
                break;
            case 'CS':
                $service = $this->getCSService();
                break;
            case 'SWITCH':
                $service = $this->getSWITCHService();
                break;
            default:
                throw new \Exception(__METHOD__ . "에서 오류발생: {$type} 지정되지 않은 형식입니다.");
                // break;
        }
        return $service;
    }
    //결제관련처리
    public function setAmount(ServerPartEntity $entity, string $callBack): ServerPartEntity
    {
        //기본처리
        if ($entity->getBilling() === PAYMENT['BILLING']['BASE']) {
            return $entity;
        }
        //월별과금용(서버->서비스정보 반영)
        if ($entity->getBilling() === PAYMENT['BILLING']['MONTH']) {
            $serverEntity = $this->getServerService()->getEntity($entity->getServerInfoUID());
            if (!$serverEntity instanceof ServerEntity) {
                throw new \Exception(__METHOD__ . "에서 오류발생: {$entity->getServerInfoUID()} 서버 정보를 찾을수 없습니다.");
            }
            $this->getServerService()->setAmount($serverEntity);
        }
        //일회성용
        if ($entity->getBilling() === PAYMENT['BILLING']['ONETIME']) {
            $paymentEntity = $this->getPaymentService()->$callBack($entity);
            $entity = $this->getModel()->modify($entity, ['payment_uid' => $paymentEntity->getPK()]);
        }
        return $entity;
    }
    //서버관련 작업
    public function attachToServer(ServerEntity $serverEntity, array $formDatas = []): void
    {
        //*서버의 Title 대소문자구분 필요->서버의 Title로 구분해서 기본부품 추가
        foreach (SERVERPART['SERVER_PARTTYPES'] as $parttype) {
            //해당 server_type의 정의된 상수값이 있으면
            if (array_key_exists($serverEntity->getTitle(), SERVERPART[$parttype])) {
                foreach (SERVERPART[$parttype][$serverEntity->getTitle()] as $part) {
                    //해당 파트정보 가져오기
                    $partEntity = $this->getPartService($parttype)->getEntity($part['UID']);
                    if (!$partEntity instanceof PartEntity) {
                        throw new \Exception(__METHOD__ . "에서 오류발생: {$part['UID']} 서버 정보를 찾을수 없습니다.");
                    }
                    //서버파트정보 생성
                    $formDatas = [];
                    $formDatas['serverinfo_uid'] = $serverEntity->getPK();
                    $formDatas["part_uid"] = $partEntity->getPK();
                    $formDatas['billing'] = PAYMENT['BILLING']['BASE'];
                    $formDatas['type'] = $parttype;
                    $formDatas['title'] = $partEntity->getTitle(); //파트 제목
                    $formDatas['amount'] = $partEntity->getPrice(); //파트 금액
                    $formDatas['cnt'] = $part["CNT"];
                    $formDatas['extra'] = $part["EXTRA"];
                    $entity = $this->getModel()->create($formDatas);
                    $this->getPartService($entity->getType())->attachToServerPart($entity);
                }
            }
        }
    }
    public function detachFromServer(ServerEntity $serverEntity): void
    {
        //서버정보에 해당하는 ServerPart정보 상태가 기본인것 제외한 모두 회수처리.
        foreach (
            $this->getEntities([
                'serverinfo_uid' => $serverEntity->getPK(),
                "billing !=" => PAYMENT['BILLING']['BASE']
            ]) as $entity
        ) {
            $this->getPartService($entity->getType())->detachFromServerPart($entity);
            $this->getModel()->delete($entity);
        }
    }
    //기본 기능부분
    // FieldForm관련용
    public function getFormOption(string $field, array $options = []): array
    {
        switch ($field) {
            case 'serverinfo_uid':
                $options = $this->getServerService()->getEntities();
                break;
            case 'part_uid':
                $partOptions = [];
                foreach (SERVERPART['ALL_PARTTYPES'] as $partType) {
                    $partOptions[$partType] = $this->getPartService($partType)->getEntities();
                }
                $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;
    }
    //부품연결정보생성
    public function create(array $formDatas): ServerPartEntity
    {
        $processor = new Proceessor(
            \Config\Database::connect(),
            $this,
            $this->getServerService(),
            $this->getPaymentService(),
            $this->getIPService(),
            $this->getSWITCHService(),
            $this->getMylogService()
        );
        return $processor->create($formDatas);
    }
    //수정
    public function modify(mixed $entity, array $formDatas): ServerPartEntity
    {
        $processor = new Proceessor(
            \Config\Database::connect(),
            $this,
            $this->getServerService(),
            $this->getPaymentService(),
            $this->getIPService(),
            $this->getSWITCHService(),
            $this->getMylogService()
        );
        return $processor->modify($entity, $formDatas);
    }
    //삭제
    public function delete(mixed $entity): ServerPartEntity
    {
        $processor = new Proceessor(
            \Config\Database::connect(),
            $this,
            $this->getServerService(),
            $this->getPaymentService(),
            $this->getIPService(),
            $this->getSWITCHService(),
            $this->getMylogService()
        );
        return $processor->delete($entity);
    }
}
