<?php

namespace App\Libraries\Adapter\API;

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

    protected function getChannel() //Codeigniter4 Service의 curlrequest이용시
    {
        if (is_null($this->_channel)) {
            // 참조: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->_channel = \Config\Services::curlrequest($options);
        }
        return $this->_channel;
    }
    protected function execute_process(): object
    {
        $options = array();
        switch ($this->getMethod()) {
            case 'POST':
                $response = $this->getChannel()->setBody($this->getDatas())->request($this->getMethod(), $this->getURL(), $options);
                break;
            case 'HEAD':
                break;
            default:
                $response = $this->getChannel()->request($this->getMethod(), $this->getURL(), $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());
    }
}
