<?php

namespace App\Libraries\MySocket\Web;

use Cloudflare\API\Auth\APIKey;
use Cloudflare\API\Adapter\Guzzle;
use App\Libraries\MySocket\WebSocket;

class CloudflareSocket extends WebSocket
{
	private static int $_request_count = 1;
	private static int $_request_max = 100;
	private static int $_request_timewait = 60;
	private $_api_email = "";
	private $_api_key = "";
	private $_client = null;
	public function __construct(string $host, string $api_email, string $api_key)
	{
		parent::__construct($host);
		$this->_api_email = $api_email;
		$this->_api_key = $api_key;
	}

	//Override
	public function getClient()
	{
		if (is_null($this->_client)) {
			$apikey = new APIKey($this->_api_email, $this->_api_key);
			$this->_client = new Guzzle($apikey);
			self::$_request_max = intval(getenv("cfmgr.request.max"));
			self::$_request_timewait = intval(getenv("cfmgr.request.timewait"));
		}
		if (self::$_request_max <= self::$_request_count) {
			log_message('warning', sprintf("--Cloudflare API Call %s초 대기 시작--", self::$_request_timewait));
			sleep(intval(getenv("cf.mgr.request.time.wait")));
			self::$_request_count = 0;
			log_message('warning', sprintf("--Cloudflare API Call %s초 대기 종료--", self::$_request_timewait));
		}
		self::$_request_count++;
		return $this->_client;
	}
}
