<?php

namespace App\Libraries\Adapter\API;

class LocalAdapter extends Adapter
{
    public function __construct($debug = false)
    {
        parent::__construct($debug);
    }

    protected function getClient() //Codeigniter4 Service의 curlrequest이용시
    {
        if (is_null($this->_client)) {
            // 참조:https://www.codeigniter.com/user_guide/libraries/curlrequest.html?highlight=curl#
            // ex:)$options = [ 'baseURI' => 'http://www.foo.com/1.0/', 'timeout' => 0, 'allow_redirects' => false, 'proxy' => '192.168.16.1:10' ]
            $options = [
                'baseURI' => $this->getServerInfo(),
                'auth' => $this->getAccountInfo(),
                'verify' => API['SSL_VERIFY'],
                'cookie' => API['COOKIE_FILE'],
            ];
            if ($this->_debug) {
                $options['debug'] = API['DEBUG_FILE'];
            }
            $this->_client = \Config\Services::curlrequest($options);
        }
        return $this->_client;
    }
    protected function requestURL(string $url, string $method, array $datas = []): object
    {
        $options = array();
        switch ($method) {
            case 'POST':
                $response = $this->getClient()->setBody($datas)->request($method, $url, $options);
                break;
            case 'HEAD':
                break;
            default:
                $response = $this->getClient()->request($method, $url, $options);
                break;
        }
        dd($response);
        if ($response->getStatusCode() != 200) {
            throw new \Exception(sprintf(
                "오류가 발생하였습니다.\n%s\n%s",
                $response->getHeaderLine('content-type'),
                $response->getBody()
            ));
        }
        return json_decode($response->getBody());
    }
}
