<?php

namespace App\Libraries\MySocket\Cloudflare;

use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Client;

class CloudflareClient extends Client
{
    const REQUEST_PERPAGE_MAX = 700;
    private static int $_request = 0;
    private static int $_request_max = 1000;
    private static int $_request_timewait = 60;
    public function __construct(array $config = [])
    {
        parent::__construct($config);
        self::$_request_max = getenv("cfmgr.request.max") ?: 1000;
        self::$_request_timewait = getenv("cfmgr.request.timewait") ?: 60;
    }
    public function get($uri, array $options = []): ResponseInterface
    {
        return $this->request('GET', $uri, $options);
    }
    public function post($uri, array $options = []): ResponseInterface
    {
        return $this->request('POST', $uri, $options);
    }
    public function put($uri, array $options = []): ResponseInterface
    {
        return $this->request('PUT', $uri, $options);
    }
    public function patch($uri, array $options = []): ResponseInterface
    {
        return $this->request('PATCH', $uri, $options);
    }
    public function delete($uri, array $options = []): ResponseInterface
    {
        return $this->request('DELETE', $uri, $options);
    }

    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++;
        $requestOptions = [];
        $requestOptions[in_array($method, ['get', 'getAsync']) ? 'query' : 'json'] = $options;
        return parent::request($method, $uri, $requestOptions);
    }
}
