<?php

namespace App\Cells\Equipment;


use App\Entities\Equipment\ServerEntity;
use App\Services\Equipment\ServerPartService;
use App\Services\Equipment\ServerService;

class ServerPartCell extends EquipmentCell
{
  private ?ServerService $_serverService = null;
  public function __construct()
  {
    parent::__construct(new ServerPartService());
  }

  final public function getServerService(): ServerService
  {
    if (!$this->_serverService) {
      $this->_serverService = new ServerService();
    }
    return $this->_serverService;
  }

  public function parttable(array $params): string
  {
    $this->getService()->setAction(__FUNCTION__);
    $this->getService()->setFormFields();
    $this->getService()->setFormFilters();
    $this->getService()->setFormRules();
    $this->getService()->setFormOptions();
    if (!array_key_exists('serverinfo_uid', $params)) {
      return "서버정보를 정의하셔야합니다.";
    }
    if (!array_key_exists('types', $params)) {
      return "부품정보 형태(Types) 리스트를 정의하셔야합니다.";
    }
    //서버정보
    $serverEntity = $this->getServerService()->getEntity($params['serverinfo_uid']);
    if (!$serverEntity instanceof ServerEntity) {
      return "[{$params['serverinfo_uid']}]의 서버정보를 확인할수없습니다..";
    }
    //PartType별 Entities
    $entities = [];
    foreach ($params['types'] as $type) {
      $entities[$type] = [];
      $entities[$type][] = $this->getService()->getEntities(['serverinfo_uid' => $serverEntity->getPK(), 'type' => $type]);
    }
    $template = array_key_exists('template', $params) ? $params['template'] : __FUNCTION__;
    return view('cells/serverpart/' . $template, [
      'serverPartCellDatas' => [
        'control'      => $this->getService()->getControlDatas(),
        'service'      => $this->getService(),
        'serverinfo_uid' => $params['serverinfo_uid'],
        'types'        => $params['types'],
        'serverEntity' => $serverEntity,
        'entities' => $entities,
      ],
    ]);
  }
}
