<?php

namespace App\Services\Part;

use App\Entities\Equipment\ServerEntity;
use App\Entities\Equipment\ServerPartEntity;
use App\Entities\Part\IPEntity;
use App\Helpers\Part\IPHelper;
use App\Models\Part\IPModel;
use App\Services\Customer\ServiceService;
use App\Services\Equipment\LineService;
use App\Services\Equipment\ServerService;
use App\Services\Part\PartService;

class IPService extends PartService
{
    private ?LineService $_lineService = null;
    private ?ServiceService $_serviceService = null;
    private ?ServerService $_serverService = null;
    public function __construct()
    {
        parent::__construct(new IPModel(), new IPHelper());
        $this->addClassName('IP');
    }
    public function getFormFields(): array
    {
        return [
            "lineinfo_uid",
            "ip",
            "price",
            "status",
        ];
    }
    public function getFormFilters(): array
    {
        return [
            'old_clientinfo_uid',
            'clientinfo_uid',
            'serverinfo_uid',
            "lineinfo_uid",
            'status'
        ];
    }
    public function getIndexFields(): array
    {
        return [
            'lineinfo_uid',
            'ip',
            'price',
            'status',
            'clientinfo_uid',
            'serverinfo_uid',
            'old_clientinfo_uid'
        ];
    }
    public function getBatchjobFields(): array
    {
        return ['status'];
    }
    final public function getLineService(): LineService
    {
        if (!$this->_lineService) {
            $this->_lineService = new LineService();
        }
        return $this->_lineService;
    }
    public function getServiceService(): ServiceService
    {
        if (!$this->_serviceService) {
            $this->_serviceService = new ServiceService();
        }
        return $this->_serviceService;
    }
    public function getServerService(): ServerService
    {
        if (!$this->_serverService) {
            $this->_serverService = new ServerService();
        }
        return $this->_serverService;
    }
    //기본기능
    //FieldForm관련용
    public function getFormOption(string $field, $options = []): array
    {
        switch ($field) {
            case 'lineinfo_uid':
                $options = $this->getLineService()->getEntities();
                break;
            case 'old_clientinfo_uid':
                $options = $this->getClientService()->getEntities();
                break;
            case 'serviceinfo_uid':
                $options = $this->getServiceService()->getEntities();
                break;
            case 'serverinfo_uid':
                $options = $this->getServerService()->getEntities();
                break;
            default:
                $options = parent::getFormOption($field, $options);
                break;
        }
        return $options;
    }
    //서비스 설정

    //List 검색용
    //OrderBy 처리
    public function setOrderBy(mixed $field = null, mixed $value = null): void
    {
        $this->getModel()->orderBy('INET_ATON(ip)', 'ASC');
        parent::setOrderBy($field, $value);
    }
    //서버관련 작업
    public function setServer(ServerEntity $serverEntity): void
    {
        $formDatas = [];
        $formDatas['clientinfo_uid']  = $serverEntity->getClientInfoUID();
        $formDatas['serviceinfo_uid'] = $serverEntity->getServiceInfoUID();
        $formDatas['serverinfo_uid']  = $serverEntity->getPK();
        $formDatas['status'] = STATUS['OCCUPIED'];
        if (!array_key_exists('status', $formDatas)) {
            throw new \Exception(__METHOD__ . ":에서 오류발생: IP상태가 설정되지 않았습니다.");
        }
        //IP정보에서 해당하는 IP가 있으면 가져와서 사용중인지 체크 후 수정
        $entity = $this->getEntity(['ip' => $serverEntity->getIP()]);
        if ($entity instanceof IPEntity) {
            if ($entity->getStatus() !== STATUS['AVAILABLE']) {
                throw new \Exception(__METHOD__ . ":에서 오류발생: {$serverEntity->getIP()}는 사용중인 IP입니다.");
            }
            $entity = parent::modify($entity, $formDatas);
        }
    }
    public function unsetServer(ServerEntity $serverEntity): void
    {
        $formDatas = [];
        $formDatas['clientinfo_uid']  = null;
        $formDatas['serviceinfo_uid'] = null;
        $formDatas['serverinfo_uid']  = null;
        $formDatas['old_clientinfo_uid']  = $serverEntity->getClientInfoUID() ?? null;
        $formDatas['status'] = STATUS['AVAILABLE'];
        if (!array_key_exists('status', $formDatas)) {
            throw new \Exception(__METHOD__ . ":에서 오류발생: IP상태가 설정되지 않았습니다.");
        }
        //IP정보가져와서 있으면 수정
        $entity = $this->getEntity(['ip' => $serverEntity->getIP()]);
        if ($entity instanceof IPEntity) {
            $entity = parent::modify($entity, $formDatas);
        }
    }

    //서버파트관련 작업
    public function setServerPart(ServerPartEntity $serverPartEntity): void
    {
        $formDatas = [];
        $formDatas['clientinfo_uid']  = $serverPartEntity->getClientInfoUID();
        $formDatas['serviceinfo_uid'] = $serverPartEntity->getServiceInfoUID();
        $formDatas['serverinfo_uid']  = $serverPartEntity->getServerInfoUID();
        $formDatas['status'] = STATUS['OCCUPIED'];
        if (!array_key_exists('status', $formDatas)) {
            throw new \Exception(__METHOD__ . ":에서 오류발생: IP상태가 설정되지 않았습니다.");
        }
        //IP정보가져오기
        $entity = $this->getEntity($serverPartEntity->getPartUID());
        if (!$entity instanceof IPEntity) {
            throw new \Exception("{$serverPartEntity->getPartUID()}에 해당하는 IP정보를 찾을수없습니다.");
        }
        if ($entity->getStatus() !== STATUS['AVAILABLE']) {
            throw new \Exception(__METHOD__ . ":에서 오류발생: {$entity->getIP()}는 사용중인 IP입니다.");
        }
        //IP정보 수정
        parent::modify($entity, $formDatas);
    }
    public function unsetServerPart(ServerPartEntity $serverPartEntity): void
    {
        $formDatas = [];
        $formDatas['clientinfo_uid']  = null;
        $formDatas['serviceinfo_uid'] = null;
        $formDatas['serverinfo_uid']  = null;
        $formDatas['old_clientinfo_uid']  = $serverPartEntity->getClientInfoUID() ?? null;
        $formDatas['status'] = STATUS['AVAILABLE'];
        if (!array_key_exists('status', $formDatas)) {
            throw new \Exception(__METHOD__ . ":에서 오류발생: IP상태가 설정되지 않았습니다.");
        }
        //IP정보가져오기
        $entity = $this->getEntity($serverPartEntity->getPartUID());
        if (!$entity instanceof IPEntity) {
            throw new \Exception("{$serverPartEntity->getPartUID()}에 해당하는 IP정보를 찾을수없습니다.");
        }
        //IP정보 수정
        parent::modify($entity, $formDatas);
    }
}
