<?php

namespace App\Libraries\MySocket;

use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Client;

class WebSocket extends MySocket
{
    private $_client = null;
    private $_cookieJar = null;
    public function __construct(string $host)
    {
        parent::__construct($host);
    }

    public function getClient()
    {
        if ($this->_client === null) {
            $this->_client = new Client(['verify' => getenv("socket.web.ssl.verify") == "true" ? true : false]);
        }
        return $this->_client;
    }

    final protected function getCookieJar()
    {
        if ($this->_cookieJar === null) {
            $this->_cookieJar = new CookieJar();
        }
        return $this->_cookieJar;
    }

    //url에 http 나 https가 포함되어 있으면 true
    final public function isContainsHttpOrHttps($url): bool
    {
        return strpos($url, 'http://') !== false || strpos($url, 'https://') !== false;
    }

    public function getResponseOptions(string $type, array $options = []): array
    {
        switch ($type) {
            case 'agent':
                // User-Agent 목록 배열
                $userAgents = [
                    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36',
                    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Safari/605.1.15',
                    'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0',
                    'Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1',
                    'Mozilla/5.0 (Linux; Android 10; SM-G973F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Mobile Safari/537.36'
                ];
                // 배열에서 랜덤으로 하나의 User-Agent 선택
                $randomUserAgent = $userAgents[array_rand($userAgents)];
                $options['headers'] = [
                    'User-Agent' => $randomUserAgent,
                ];
                break;
        }
        return $options;
    }
    public function getResponse(string $url, $method = "get", array $options = []): mixed
    {
        //url에 http 나 https가 포함되어 있지않으면
        if (!($this->isContainsHttpOrHttps($url))) {
            $url = $this->gethost() . $url;
        }
        //기본 Option
        $options['cookies'] = $this->getCookieJar(); //쿠키값
        $options['timeout'] = getenv("socket.web.timeout"); // 5초 안에 응답이 없으면 타임아웃
        log_message("debug", __FUNCTION__ . "=> 호출 Socket URL-> " . $url);
        return $this->getClient()->$method($url, $options);
    }

    public function getContent(string $url, $method = "get", array $options = []): string
    {
        log_message("debug", __FUNCTION__ . "=> 호출 URL:" . $url);
        $response = $this->getResponse($url, $method, $options);
        if ($response->getStatusCode() == 200) {
            // return $response->getBody()->getContents();
            return $response->getBody();
        }
        throw new \Exception("error", __FUNCTION__ . "=> {$url} 접속실패: " . $response->getStatusCode());
    }
}
