<?php

namespace App\Cells\Equipment;


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
  {
    $result = "";
    if (array_key_exists('serverinfo_uid', $params)) {
      $this->getService()->setAction(__FUNCTION__);
      $this->getService()->setFormFields();
      $this->getService()->setFormFilters();
      $this->getService()->setFormRules();
      $this->getService()->setFormOptions();
      // dd($params);
      //서버정보
      $serverEntity = $this->getServerService()->getEntity($params['serverinfo_uid']);
      if (!$serverEntity) {
        return "[{$params['serverinfo_uid']}]에 해당하는 서버정보가 지정되지 않았거나 존재하지 않습니다.";
      }
      //서버파트정보
      $serverPartEntities = $this->getService()->getEntities(['serverinfo_uid' => $serverEntity->getPK(),]);
      $entities           = [];
      foreach ($serverPartEntities as $entity) {
        if (!array_key_exists($entity->getType(), $entities)) {
          $entities[$entity->getType()] = [];
        }
        $entities[$entity->getType()][] = $entity;
      }
      $template = array_key_exists('template', $params) ? $params['template'] : __FUNCTION__;
      $result = view('cells/serverpart/' . $template, [
        'serverPartCellDatas' => [
          'control'      => $this->getService()->getControlDatas(),
          'service'      => $this->getService(),
          'serverinfo_uid' => $params['serverinfo_uid'],
          'entities'     => $entities,
          'serverEntity' => $serverEntity,
          'types'        => $params['types'],
        ],
      ]);
    }
    return $result;
  }
}
