<?php

namespace App\Controllers\CLI\HPILO;

use App\Models\HPILOModel;
use App\Entities\HPILOEntity;

class HPILO4
{
	private $_adapter = null;
	private function getAdapter(HPILOEntity $entity)
	{
		if (is_null($this->_adapter)) {
			$adapterClass = getenv('hpilo.adapter');
			$this->_adapter[$entity->getPrimaryKey()] = new $adapterClass($entity);
		}
		return $this->_adapter[$entity->getPrimaryKey()];
	}

	final public function execute()
	{
		try {
			$model = new HPILOModel();
			$entitys = $model->asObject(HPILOEntity::class)->where(['status' => 'use'])->findAll();
			//transation처리
			// $this->getAuthModel()->db->transBegin();
			foreach ($entitys as $entity) {
				$ilo = new \App\Libraries\HPILO\HPILO4($this->getAdapter($entity));
				$entity = $ilo->refresh($entity);
				if ($entity->hasChanged()) {
					if (!$model->save($entity)) {
						log_message("error", __FUNCTION__ . "에서 호출:" . $model->getLastQuery());
						log_message("error", implode("\n", $model->errors()));
						throw new \Exception(__FUNCTION__ . " 오류 발생.\n" . var_export($model->errors(), true));
					}
					$message = "{$entity->getTitle()} " . __FUNCTION__ . " 완료하였습니다.";
					log_message("debug", $message);
				}
			}
			//transation 완료
			// $this->getAuthModel()->db->transCommit();
			$message = __METHOD__ . "에서 ILO4 Reload 총:" . count($entitys) . " 완료하였습니다.";
			echo $message;
		} catch (\Exception $e) {
			//transaction 오류복구
			// $this->getAuthModel()->db->transRollback();
			$message = __METHOD__ . "에서 ILO4 Reload 오류\n" . $e->getMessage();
			log_message("error", $message);
			echo $message;
		}
	}
}
