<?php

namespace App\Controllers\Admin;

use App\Models\HPILOModel;
use App\Entities\HPILOEntity;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Libraries\API\HPILO\HPILO4;

class HPILOController extends \App\Controllers\Admin\AdminController
{
    private $_adapter = null;
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        $this->_backend = service('hpilo');
        parent::initController($request, $response, $logger);
        $this->_viewPath .= strtolower($this->_backend->getClassName());
    }

    private function getAdapter(HPILOEntity $entity)
    {
        if (is_null($this->_adapter)) {
            $adapterClass = getenv('hpilo.api.adapter') ?: "\App\Libraries\Adapter\API\GuzzleAdapter";
            $this->_adapter = new $adapterClass(getenv('hpilo.api.debug') ?: false);
            $this->_adapter->setServerInfo($entity->getIP(), $entity->getPort());
            $this->_adapter->setAccountInfo($entity->getID(), $entity->getPassword());
        }
        return $this->_adapter;
    }

    //Insert관련
    protected function insert_validate()
    {
        parent::insert_validate();
        //IP형식 검사 모든 ip형식 사용가능
        if (!isIPAddress_CommonHelper($this->_viewDatas['fieldDatas']['ip'], 'all')) {
            throw new \Exception("{$this->_viewDatas['title']}의 all, {$this->_viewDatas['fieldDatas']['ip']} 형식 오류");
        }
    }

    ////추가 Action
    final public function console($uid)
    {
        try {
            $entity = $this->_model->getEntity([$this->_model->getPrimaryKey() => $uid]);
            $ilo = new HPILO4($this->getAdapter($entity));
            $this->_viewDatas['SessionKey'] = $ilo->console();
            $this->_viewDatas['entity'] = $entity;
            return view($this->_viewPath . '/console_iframe', $this->_viewDatas);
        } catch (\Exception $e) {
            return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']))->with('return_message', $e->getMessage());
        }
    }

    final public function reset($uid, string $type)
    {
        $msg = "";
        try {
            $entity = $this->_model->getEntity([$this->_model->getPrimaryKey() => $uid]);
            if (!in_array($type, ["On", "Off", "Restart"])) {
                throw new \Exception(__FUNCTION__ . "에서 {$type}은 기능은 없습니다.");
            }
            $ilo = new HPILO4($this->getAdapter($entity));
            $results = $ilo->reset($type);
            $msg = "{$this->_viewDatas['title']}에서 " . __FUNCTION__ . " 완료하였습니다.";
        } catch (\Exception $e) {
            $msg = "{$this->_viewDatas['title']}에서 " . __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage();
            log_message("error", $e->getMessage());
            log_message("error", var_export($this->_viewDatas['fieldDatas'], true));
        } finally {
            $this->_session->setFlashdata("return_message", $msg);
            return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']));
        }
    }

    final public function reload($uid)
    {
        $msg = "";
        try {
            $entity = $this->_model->getEntity([$this->_model->getPrimaryKey() => $uid]);
            $ilo = new HPILO4($this->getAdapter($entity));
            $entity = $ilo->reload($entity);
            if ($entity->hasChanged()) {
                if (!$this->_model->save($entity)) {
                    log_message("error", __FUNCTION__ . "에서 호출:" . $this->_model->getLastQuery());
                    log_message("error", implode("\n", $this->_model->errors()));
                    throw new \Exception(__FUNCTION__ . " 오류 발생.\n" . var_export($this->_model->errors()));
                }
            }
            $msg = "{$this->_viewDatas['title']}에서 " . __FUNCTION__ . " 완료하였습니다.";
        } catch (\Exception $e) {
            $msg = "{$this->_viewDatas['title']}에서 " . __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage();
            log_message("error", $e->getMessage());
            log_message("error", var_export($this->_viewDatas['fieldDatas'], true));
        } finally {
            $this->_session->setFlashdata("return_message", $msg);
            return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']));
        }
    }
}
