<?php

namespace App\Services\Equipment;

use App\Entities\Customer\ServiceEntity;
use App\Entities\Equipment\ServerEntity;
use App\Helpers\Equipment\ServerHelper;
use App\Models\Equipment\ServerModel;
use App\Services\Equipment\EquipmentService;

class ServerService extends EquipmentService
{
    private ?ServerPartService $_serverPartService = null;
    public function __construct()
    {
        parent::__construct(new ServerModel(), new ServerHelper());
        $this->addClassName('Server');
    }
    public function getFormFields(): array
    {
        return [
            "clientinfo_uid",
            "serviceinfo_uid",
            "code",
            "type",
            "title",
            "price",
            "manufactur_at",
            "format_at",
            "status",
        ];
    }
    public function getFormFilters(): array
    {
        return [
            "clientinfo_uid",
            "serviceinfo_uid",
            "type",
            "title",
            "status"
        ];
    }
    public function getIndexFields(): array
    {
        return [
            'clientinfo_uid',
            'serviceinfo_uid',
            "type",
            'title',
            'price',
            'manufactur_at',
            "format_at",
            'status',
        ];
    }
    public function getIndexFilters(): array
    {
        return [
            'clientinfo_uid',
            'serviceinfo_uid',
            'type',
            "title",
            'status'
        ];
    }
    public function getBatchjobFields(): array
    {
        return ['clientinfo_uid', 'status'];
    }
    final public function getServerPartService(): ServerPartService
    {
        if (!$this->_serverPartService) {
            $this->_serverPartService = new ServerPartService();
        }
        return $this->_serverPartService;
    }
    //partEntity 정보 추가
    protected function getEntity_process(mixed $entity): ServerEntity
    {
        if (!($entity instanceof ServerEntity)) {
            throw new \Exception(__METHOD__ . "에서 형식오류:ServerEntity만 허용됩니다.");
        }
        return $entity;
    }
    //기본 기능부분
    //FieldForm관련용
    //create용 장비코드 마지막번호 가져오기
    final public function getLastestCode(string $format, int $default): string
    {
        return $this->getModel()->getLastestCode($format, $default);
    }
    final public function codeCheck(array $formDatas)
    {
        //코드 패턴체크
        $pattern = env("Server.Prefix.code.pattern", false);
        if (!$pattern) {
            throw new \Exception(__METHOD__ . "에서 code의 prefix[Server.Prefix.code.pattern]가 정의되지 않았습니다.");
        }
        if (!array_key_exists('code', $formDatas)) {
            throw new \Exception("Server코드가 정의되지 않았습니다");
        }
        if (!preg_match($pattern, $formDatas['code'])) {
            throw new \Exception("Server코드[{$formDatas['code']}의 형식이 맞지않습니다");
        }
    }
    //Service별 수정
    public function modify(mixed $entity, array $formDatas): ServerEntity
    {
        //서비스정보가져오기
        $serviceEntity = null;
        if (array_key_exists('serviceEntity', $formDatas)) {
            $serviceEntity = $formDatas['serviceEntity'];
        } else {
            if (!array_key_exists('serviceinfo_uid', $formDatas)) {
                throw new \Exception("서비스 정보가 지정되지 않았습니다.");
            }
            $serviceEntity = $this->getServiceService()->getEntity($formDatas['serviceinfo_uid']);
        }
        if ($serviceEntity instanceof ServiceEntity) {
            //서비스상태에 따라
            if ($formDatas['status'] === STATUS['AVAILABLE']) {
                //사용가능
                $formDatas["clientinfo_uid"]  = null;
                $formDatas["serviceinfo_uid"] = null;
            } else {
                //사용중 , 일시정지
                $formDatas["clientinfo_uid"]  = $serviceEntity->getClientInfoUID();
                $formDatas["serviceinfo_uid"] = $serviceEntity->getPK();
            }
        }
        //서버정보수정
        return $this->getEntity_process(parent::modify($entity, $formDatas));
    }
    //삭제
    public function delete(mixed $entity): ServerEntity
    {
        //기존 ServerPart정보 삭제
        foreach ($this->getServerPartService()->getEntities(['serverinfo_uid' => $entity->getPK()]) as $serverPartEntity) {
            $this->getServerPartService()->delete($serverPartEntity);
        }
        return parent::delete($entity);
    }
    //List 검색용
    //OrderBy 처리
    public function setOrderBy(mixed $field = null, mixed $value = null): void
    {
        $this->getModel()->orderBy("code ASC,title ASC");
        parent::setOrderBy($field, $value);
    }
}
