<?php

namespace App\Services\Part;

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


abstract class PartType1Service 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
    {
        //부품정보가져오기
        /** @var PartEntity $entity IDE에 entity type알려주기*/
        $entity = $this->getPartEntityByServerPart($serverPartEntity);
        //파트정보의 사용가능한 갯수 , 사용갯수 비교
        if ($entity->getAvailable() <  $serverPartEntity->getCnt()) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 현재 {$entity->getTitle()}는 사용가능 갯수[{$entity->getAvailable()}]보다 지정하신 갯수({$serverPartEntity->getCnt()})가 더 많습니다.");
        }
        $formDatas         = [];
        $formDatas['used'] = $entity->getUsed() + $serverPartEntity->getCnt();
        return parent::modify_process($entity, $formDatas);
    }
    public function modifyServerPart(ServerPartEntity $oldServerPartEntity, ServerPartEntity $serverPartEntity): PartEntity
    {
        if ($oldServerPartEntity->getPartUid() != $serverPartEntity->getPartUid()) {
            $this->detachFromServerPart($oldServerPartEntity);
            $this->attachToServerPart($serverPartEntity);
        }
        // PartUID가 바뀌지 않고 다른 값만 바뀐경우
        //부품정보가져오기
        /** @var PartEntity $entity IDE에 entity type알려주기*/
        $entity = $this->getPartEntityByServerPart($serverPartEntity);
        //기존 파트 정보와 신규 파트정보의 사용한 갯수 비교
        $formDatas = [];
        if ($oldServerPartEntity->getCnt() < $serverPartEntity->getCnt()) {
            $formDatas['used'] = $entity->getUsed() + ($serverPartEntity->getCnt() - $oldServerPartEntity->getCnt());
        } else {
            $formDatas['used'] = $entity->getUsed() + ($oldServerPartEntity->getCnt() - $serverPartEntity->getCnt());
        }
        return parent::modify_process($entity, $formDatas);
    }
    public function detachFromServerPart(ServerPartEntity $serverPartEntity, array $formDatas = []): PartEntity
    {
        //부품정보가져오기
        /** @var PartEntity $entity IDE에 entity type알려주기*/
        $entity = $this->getPartEntityByServerPart($serverPartEntity);
        //파트정보의 사용된 갯수 , 회수용 갯수 비교
        if ($entity->getUsed() < $serverPartEntity->getCnt()) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 현재 {$entity->getTitle()}는 사용된 갯수[{$entity->getUsed()}]보다 지정하신 갯수({$serverPartEntity->getCnt()})가 더 많습니다.");
        }
        $formDatas = [];
        $formDatas['used'] = $entity->getUsed() - $serverPartEntity->getCnt();
        return parent::modify_process($entity, $formDatas);
    }
}
