<?php

namespace App\Libraries\Adapter\API;

use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\ClientException;
// 참고:https://github.com/SyntaxPhoenix/iloclient
class GuzzleAPI extends API
{
    private $_jar = null;
    public function __construct($debug = false)
    {
        parent::__construct($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 getChannel() //Guzzle이용시
    {
        if (is_null($this->_channel)) {
            // 참조: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' => API['SSL_VERIFY'],
                'cookie' => API['COOKIE_FILE'],
                // \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->_channel = new \GuzzleHttp\Client($options);
        }
        return $this->_channel;
    }

    protected function execute_process(): object
    {
        try {
            $options = array();
            if ($this->_debug) {
                $options['debug'] = fopen('php://stderr', 'w'); //or true
            }
            switch ($this->getMethod()) {
                case 'POST':
                    $options['json'] = $this->getDatas();
                    break;
                case 'HEAD':
                    break;
            }
            $response = $this->getChannel()->request($this->getMethod(), $this->getURL(), $options);
            if ($response->getStatusCode() != 200) {
                throw new \Exception(sprintf(
                    "오류가 발생하였습니다.\n%s\n%s",
                    $response->getHeaderLine('content-type'),
                    $response->getBody()
                ));
            }
            $this->setLocalCookie($this->getURL());
            // 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())
            );
        }
    }
}
