<?php

namespace App\Services\Part;

use App\Entities\Equipment\ServerPartEntity;
use App\Entities\Part\PartEntity;
use App\Models\CommonModel;

abstract class PartType2Service extends PartService
{
    protected function __construct(CommonModel $model)
    {
        parent::__construct($model);
    }
    abstract public function getPartEntityByServerPart(ServerPartEntity $serverPartEntity): PartEntity;
    //서버파트관련 작업
    public function attachToServerPart(ServerPartEntity $serverPartEntity, array $formDatas = []): PartEntity
    {
        $formDatas['clientinfo_uid']  = $serverPartEntity->getClientInfoUid();
        $formDatas['serviceinfo_uid'] = $serverPartEntity->getServiceInfoUid();
        $formDatas['serverinfo_uid']  = $serverPartEntity->getServerInfoUid();
        $formDatas['status'] = STATUS['OCCUPIED'];
        //파트정보가져오기
        $entity = $this->getPartEntityByServerPart($serverPartEntity);
        //상태확인
        if ($entity->getStatus() !== STATUS['AVAILABLE']) {
            throw new \Exception(static::class . '->' . __FUNCTION__ . ":에서 오류발생: {$entity->getTitle()}는 사용중입니다.");
        }
        //파트정보 수정
        return parent::modify_process($entity, $formDatas);
    }
    public function modifyServerPart(ServerPartEntity $oldServerPartEntity, ServerPartEntity $serverPartEntity, array $formDatas = []): PartEntity
    {
        // 파트정보가 변경되었으면
        if ($oldServerPartEntity->getPartUid() != $serverPartEntity->getPartUid()) {
            $this->detachFromServerPart($oldServerPartEntity);
            $this->attachToServerPart($serverPartEntity);
        }
        return $this->getPartEntityByServerPart($serverPartEntity);
    }
    public function detachFromServerPart(ServerPartEntity $serverPartEntity, array $formDatas = []): PartEntity
    {
        $formDatas['clientinfo_uid']  = null;
        $formDatas['serviceinfo_uid'] = null;
        $formDatas['serverinfo_uid']  = null;
        $formDatas['status'] = STATUS['AVAILABLE'];
        //파트정보가져오기
        $entity = $this->getPartEntityByServerPart($serverPartEntity);
        //파트정보 수정
        return parent::modify_process($entity, $formDatas);
    }
}
