<?php

namespace App\Libraries\MySocket;

use Psr\Http\Message\ResponseInterface;
use App\Entities\Cloudflare\AuthEntity;

class CloudflareSocket extends MySocket
{
	private static int $_request = 0;
	private static int $_request_max = 1000;
	public static int $_request_perpage_max = 700;
	private static int $_request_timewait = 60;
	public function __construct(AuthEntity $auth_entity)
	{
		parent::__construct([
			'base_uri' => 'https://api.cloudflare.com/client/v4/',
			'headers' => [
				'X-Auth-Email' => $auth_entity->getID(),
				'X-Auth-Key' => $auth_entity->getAuthKey(),
				'Content-Type' => 'application/json',
			]
		]);
	}

	final public function request(string $method, $uri = '', array $options = []): ResponseInterface
	{
		if (self::$_request >= self::$_request_max) {
			log_message('warning', sprintf("--Cloudflare API Call %s초 대기 시작--", self::$_request_timewait));
			sleep(intval(self::$_request_timewait));
			self::$_request = 0;
			log_message('warning', sprintf("--Cloudflare API Call %s초 대기 종료--", self::$_request_timewait));
		}
		self::$_request++;
		return parent::request($method, $uri, $options);
	}
}
