<?php

namespace App\Libraries\Cloudflare;

use App\Models\Cloudflare\AuthModel;
use App\Models\Cloudflare\AccountModel;
use App\Libraries\MySocket\CloudflareSocket;
use App\Libraries\CommonLibrary;
use App\Entities\Cloudflare\AuthEntity;

abstract class Cloudflare extends CommonLibrary
{
	private $_auth_entity = null;
	private $_authModel = null;
	private $_accountModel = null;
	protected function __construct(AuthEntity $auth_entity)
	{
		$this->_auth_entity = $auth_entity;
		parent::__construct();
	}
	abstract protected function getArrayByResult($result, array $formDatas = []): array;
	final public function getMySocket(): CloudflareSocket
	{
		if ($this->_mySocket === null) {
			$this->_mySocket = new CloudflareSocket($this->getAuthEntity());
		}
		return $this->_mySocket;
	}
	final protected function getAuthEntity(): AuthEntity
	{
		if ($this->_auth_entity === null) {
			throw new \Exception(__FUNCTION__ . "에서 인증정보가 없습니다.");
		}
		return $this->_auth_entity;
	}
	final protected function getAuthModel(): AuthModel
	{
		if ($this->_authModel === null) {
			$this->_authModel = new AuthModel();
		}
		return $this->_authModel;
	}
	final protected function getAccountModel(): AccountModel
	{
		if ($this->_accountModel === null) {
			$this->_accountModel = new AccountModel();
		}
		return $this->_accountModel;
	}
	final protected function reload_procedure($uri): array
	{
		$page = 1; //1부터 시작
		$results = [];
		do {
			$query = [
				'page' => $page,
				'per_page' => $this->getMySocket()::$_request_perpage_max,
				'match' => 'all',
			];
			$response = $this->getMySocket()->get($uri, $query);
			$cf = json_decode($response->getBody());
			if (!$cf->success) {
				$message = __FUNCTION__ . "에서 실패:\nresponse:" . var_export($cf, true);
				log_message("error", $message);
				throw new \Exception($message);
			}
			$results = array_merge($results, $cf->result);
			if (count($cf->result) < $this->getMySocket()::$_request_perpage_max) {
				break;
			}
			$page++;
		} while (true);
		return $results;
	}
}
