<?php

namespace App\Controllers\Admin\Equipment;

use App\Entities\Equipment\LineEntity;
use App\Helpers\Equipment\LineHelper;
use App\Services\Equipment\IPService;

use App\Services\Equipment\LineService;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class LineController extends EquipmentController
{
    private ?IpService $_ipService = null;
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->content_title      = lang("{$this->getService()->getClassName()}.title");
        $this->class_path .= $this->getService()->getClassName();
        $this->uri_path .= strtolower($this->getService()->getClassName('/')) . '/';
        // $this->view_path .= strtolower($this->getService()->getClassName()) . DIRECTORY_SEPARATOR;

    }
    public function getService(): LineService
    {
        if (!$this->_service) {
            $this->_service = new LineService();
        }
        return $this->_service;
    }
    public function getHelper(): LineHelper
    {
        if (!$this->_helper) {
            $this->_helper = new LineHelper();
        }
        return $this->_helper;
    }
    final public function getIPService(): IpService
    {
        if (!$this->_ipService) {
            $this->_ipService = new IpService();
        }
        return $this->_ipService;
    }
    //Index,FieldForm관련

    //생성
    protected function create_process(array $formDatas): LineEntity
    {
        //Line 등록
        if (!$this->getHelper()->isValidCIDR($formDatas['bandwith'])) {
            throw new \Exception("{$formDatas['bandwith']}는 CIDR 형식에 부합되지 않습니다.");
        }
        //부모처리
        $entity = parent::create_process($formDatas);
        //Prefixed IP to array 자동 등록
        foreach ($this->getHelper()->cidrToIpRange($formDatas['bandwith']) as $ip) {
            $this->getIPService()->createByLineInfo($entity, $ip);
        }
        return $entity;
    }
}
