<?php

namespace App\Libraries\MySocket;

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

class WebLibrary extends MySocketLibrary
{
    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 getContent(string $url, array $options = []): string
    {
        //url에 http 나 https가 포함되어 있지않으면
        if (!($this->isContainsHttpOrHttps($url))) {
            $url = $this->gethost() . $url;
        }
        log_message("debug", "Socket URL-> " . $url);
        $response = $this->getClient()->get($url, $options);
        if ($response->getStatusCode() != 200) {
            throw new \Exception("error", "{$url} 접속실패: " . $response->getStatusCode());
        }
        return $response->getBody()->getContents();
    }

    // 로그인 메서드
    public function login($url, $username, $password): bool
    {
        $response = $this->getClient()->post($this->gethost() . $url, [
            'form_params' => [
                'username' => $username,
                'password' => $password,
            ],
            'cookies' => $this->getCookieJar(),
        ]);
        if ($response->getStatusCode() == 200) {
            log_message("notice", "로그인 성공");
            if ($this->getDebug()) {
                echo var_dump($response);
            }
            return true;
        } {
            log_message("error", "로그인 실패: " . $response->getStatusCode());
            return false;
        }
    }

    // 파일 다운로드 메서드
    public function download(string $url): array
    {
        $fileNames = explode('/', $url);
        if (!is_array($fileNames) || !count($fileNames)) {
            throw new \Exception("Socket URL Error:" . $this->getHost() . $url);
        }
        $fileName = array_pop($fileNames);
        if (!$this->getDebug()) {
            $content = $this->getContent($url, [
                'cookies' => $this->getCookieJar(),
                // 'sink'    => $savePath,
            ]);
            if (!$content) {
                throw new \Exception("{$fileName} 파일 다운로드 실패");
            }
            log_message("notice", "{$fileName} 파일이 다운로드되었습니다!");
        }
        return array($fileName, $content);
    }
}
