<?php

namespace App\Services\Customer\ServiceItemLink;

use App\Entities\Customer\ServiceItemEntity;
use App\Entities\Equipment\Part\IpEntity;
use App\Services\Equipment\Part\IpService;

class ServiceItemLinkIpService extends ServiceItemLinkService
{
    private ?IpService $_ipService = null;
    public function __construct(mixed $request = null)
    {
        parent::__construct($request);
    }

    public function getIpService(): IpService
    {
        if (!$this->_ipService) {
            $this->_ipService = new IpService($this->request);
        }
        return $this->_ipService;
    }

    public function getFormFieldOption(string $field, array $options = []): array
    {
        return $this->getIpService()->getEntities();
    }

    public function create(array $formDatas, mixed $entity = null): ServiceItemEntity
    {
        //ip의 경우 서비스중으로 설정작업
        $this->getIpService()->setStatus($formDatas['item_uid'], IpEntity::STATUS_OCCUPIED);
        return parent::create($formDatas, $entity);;
    }
    public function modify(mixed $entity, array $formDatas): ServiceItemEntity
    {
        //item_uid가 기존과 다를경우 //toggle,batchjob의 경우 $formDatas에 item_uid가 없을수도 있음
        if (array_key_exists('item_uid', $formDatas) && $formDatas['item_uid'] !== $entity->getItemUid()) {
            //item_uid의 경우 기존item_uid는 사용가능으로 설정작업
            $this->getIpService()->setStatus($entity->getItemUid(), IpEntity::STATUS_AVAILABLE);
            //item_uidd의 경우 변경된 item_uid는 서비스중으로 설정작업
            $this->getIpService()->setStatus($formDatas['item_uid'], IpEntity::STATUS_OCCUPIED);
        }
        return parent::modify($entity, $formDatas);
    }
    public function delete(mixed $entity): bool
    {
        //item_uid의 경우 기존item_uid는 사용가능으로 설정작업
        $this->getIpService()->setStatus($entity->getItemUid(), IpEntity::STATUS_AVAILABLE);
        return parent::delete($entity);
    }
}
