<?php 

namespace App\Bundle\Infoclinica;

use GuzzleHttp\Client as gzClient;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Message\MessageFactoryInterface;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;

/**
 * @author Ivan Alexandrov <yahve1989@gmail.com>
 */
class Client
{
    public static $instance = NULL;
    private $cookieJar = NULL;
    private $client = NULL;
    private $baseUri = NULL;
    private $path = NULL;
    public $dataResponse = [];
    private $method = 'GET';
    public $params = [
        'debug' => false,
        'verify' => false,
        'http_errors' => false,
        'allow_redirects' => [
            'max' => 10,
            'strict' => true,
            'referer' => true,
            'track_redirects' => true,
        ],
    ];


    /**
     * @return type $instance
     */
    public static function init($baseUri = 'https://widget.sovamed.ru')
    {
        if (self::$instance === null) {
            self::$instance = new self();
            self::$instance->setBaseUri($baseUri);

            $request = SymfonyRequest::createFromGlobals();
            
            /*$cookieJar = CookieJar::fromArray([
                'WR_SESSION' => $request->cookies->get('WR_SESSION'),
                'WR_DETAIL' => $request->cookies->get('WR_DETAIL'),
                'PLAY_SESSION' => $request->cookies->get('PLAY_SESSION'),
            ], '.sovamed.ru');
            */
            // self::$instance->params['cookies'] = $cookieJar;
            self::$instance->client = new gzClient([
                'cookies' => false,
                'base_uri' => self::$instance->baseUri,
                'timeout'  => 60,
                'headers' => [
                    'Origin' => self::$instance->baseUri,
                    'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0',
                    'Accept-Language' => 'ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3',
                    'Accept' => 'application/json, text/javascript, */*; q=0.01',
                    'Content-Type' => 'application/json; charset=UTF-8',
                    'X-Requested-With' => 'XMLHttpRequest',
                    'X-Integration-Type' => 'WEBSDK'
                ]
            ]);
        }
        
        return self::$instance;
    }

    public function setAuth($username, $password)
    {
        $this->params['headers']['Authorization'] = 'Basic ' . base64_encode("$username:$password");
        return $this;
    }

    public function setHeader($key, $value)
    {
        $this->params['headers'][$key] = $value;
        return $this;
    }

    public function setBaseUri($url)
    {
        $this->baseUri = $url;
        return $this;
    }

    /**
     * @param type $params
     */
    public function setParams($params)
    {
        $this->params = $params; 
        $this->method = 'POST';
        return $this;
    }

    /**
     * @param type $formParams
     */
    public function setBodyParams($formParams)
    {
        $this->params['body'] = json_encode($formParams); 
        $this->method = 'POST';
        return $this;
    }

    public function clearParams()
    {
        unset($this->params['form_params']);
        unset($this->params['body']);
        $this->method = 'GET';
        return $this;
    }

    public function setMethod($method)
    {
        $this->method = $method;
        return $this;
    }

    /**
     * @return type
     */
    public function setFormParams($params = [])
    {
        $this->params['form_params'] = $params;
        $this->method = 'POST';
        return $this;
    }

    /**
     * @param type $path
     */
    public function setPath($path)
    {
        $this->path = $path;
        return $this;
    }

    /**
     * @return type string
     */
    public function exec()
    {

        $response = $this->client->request($this->method, $this->path, $this->params); 

        // if (in_array($this->path, ['/registration', '/login'])) {
        //     if (!empty($cookie = $this->params['cookies']->getCookieByName('WR_SESSION')))
        //         $this->dataResponse['cookies']['WR_SESSION'] = $cookie->getValue();

        //     if (!empty($cookie = $this->params['cookies']->getCookieByName('WR_DETAIL')))
        //         $this->dataResponse['cookies']['WR_DETAIL'] = $cookie->getValue();

        //     if (!empty($cookie = $this->params['cookies']->getCookieByName('PLAY_SESSION')))
        //         $this->dataResponse['cookies']['PLAY_SESSION'] = $cookie->getValue();
            
        //     if (!empty($cookie = $this->params['cookies']->getCookieByName('PLAY_FLASH')))
        //         $this->dataResponse['cookies']['PLAY_FLASH'] = $cookie->getValue();
        // }   

        $this->dataResponse['response'] = json_decode($response->getBody()->getContents(), true);
        
        return $this;
    }

    public function raw($body = [])
    {
        $jar = new \GuzzleHttp\Cookie\CookieJar;

        $response = $this->client->post($this->baseUri . $this->path, [
            'cookies' => $jar,
            'headers' => [
                'User-Agent' => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:88.0) Gecko/20100101 Firefox/88.0',
                'Content-Type' => 'application/json', 
                'X-Requested-With' => 'XMLHttpRequest',
                'X-Integration-Type' => 'WEBSDK'
            ],
            'body' => json_encode($body)
        ]);
        
        return $response->getBody()->getContents();
    }
}
