<?php

namespace App\Libraries\Adapter\API;

use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\ClientException;
// 참고:https://github.com/SyntaxPhoenix/iloclient
class GuzzleAdapter extends Adapter
{
    private $_jar = null;
    public function __construct($entity, $debug = false)
    {
        parent::__construct($entity, $debug);
    }
    private function getCookieJar(): \GuzzleHttp\Cookie\CookieJar
    {
        if (is_null($this->_jar)) {
            $this->_jar = new \GuzzleHttp\Cookie\CookieJar();
        }
        return $this->_jar;
    }
    protected function setLocalCookie(): void
    {
        // dd($this->getCookieJar(), true);
        foreach (['Key', 'Lang', 'Url'] as $key) {
            log_message('debug', var_export($this->getCookieJar()->getCookieByName('session' . $key), true));
        }
    }

    protected function getClient() //Guzzle이용시
    {
        if (is_null($this->_client)) {
            // 참조:https://docs.guzzlephp.org/en/stable/request-options.html
            // ex:)$options = [ 'base_uri' => 'http://www.foo.com/1.0/', 'timeout' => 0, 'allow_redirects' => false, 'proxy' => '192.168.16.1:10' ]
            $options = [
                'base_uri' => $this->getServerInfo(),
                'auth' => $this->getAccountInfo(),
                'verify' => $this->isSSLVerifiy(),
                'cookie' => $this->getCookieFile(),
                // \GuzzleHttp\RequestOptions::ALLOW_REDIRECTS => [
                //     'max'             => 10,        // allow at most 10 redirects.
                //     'strict'          => true,      // use "strict" RFC compliant redirects.
                //     'referer'         => true,      // add a Referer header
                //     'track_redirects' => true,
                // ],
            ];
            $this->_client = new \GuzzleHttp\Client($options);
        }
        return $this->_client;
    }

    protected function requestURL(string $url, string $method, array $datas = []): object
    {
        try {
            $options = array();
            if ($this->_debug) {
                $options['debug'] = fopen('php://stderr', 'w'); //or true
            }
            switch ($method) {
                case 'POST':
                    $options['json'] = $datas;
                    break;
                case 'HEAD':
                    break;
            }
            $response = $this->getClient()->request($method, $url, $options);
            if ($response->getStatusCode() != 200) {
                throw new \Exception(sprintf(
                    "오류가 발생하였습니다.\n%s\n%s",
                    $response->getHeaderLine('content-type'),
                    $response->getBody()
                ));
            }
            $this->setLocalCookie($url);
            // echo $response->getHeaderLine('content-type'); // 'application/json; charset=utf8'
            // echo $response->getBody()=>'{"id": 1420053, "name": "guzzle", ...}
            return json_decode($response->getBody()->getContents());
        } catch (ClientException $e) {
            throw new \Exception(
                Psr7\Message::toString($e->getRequest()) . "\n" .
                    Psr7\Message::toString($e->getResponse())
            );
        }
    }
}
