<?php
namespace App\Model\Services;

use App\Model\Exceptions\Steam\AuthenticationFailedException;
use App\Model\Exceptions\Steam\AuthenticationRequiredException;
use App\Model\Exceptions\Steam\EmptyResponseException;
use App\Model\Exceptions\Steam\ServerResponseException;
use App\Model\Crates\SteamProfile;
use Bitbang\Http\Clients\CurlClient;
use Bitbang\Http\Request;
use LightOpenID;

class SteamApiService
{
    protected $apiKey;

    protected static $providerUrl = 'http://steamcommunity.com/openid';

    /**
     * SteamService constructor.
     * @param $apiKey
     */
    public function __construct($apiKey)
    {
        $this->apiKey = $apiKey;
    }

    /**
     * @param $backlink
     * @return String
     */
    public function getAuthRedirectUrl(String $backlink)
    {
        $openId = new LightOpenID($backlink);
        $openId->identity = self::$providerUrl;
        return $openId->authUrl();
    }

    /**
     * @param $backlink
     * @return String
     * @throws AuthenticationFailedException
     * @throws AuthenticationRequiredException
     */
    public function retrieveSteamId(String $backlink) : String
    {
        $openId = new LightOpenID($backlink);

        if (!$openId->mode) {
            throw new AuthenticationRequiredException();
        }

        if (!$openId->validate()) {
            throw new AuthenticationFailedException();
        }

        return str_replace(self::$providerUrl . '/id/', '', $openId->identity);
    }

    public function retrievePlayerProfile($steamId)
    {
        $url = 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/';
        $url .= '?key=' . $this->apiKey;
        $url .= '&steamids=' . $steamId;

        $httpRequest = new Request('GET', $url);
        $client = new CurlClient();
        $httpResponse = $client->process($httpRequest);
        if ($httpResponse->getCode() !== 200) {
            throw new ServerResponseException();
        }

        $result = json_decode($httpResponse->getBody());
        if (!isset($result->response->players[0])) {
            throw new EmptyResponseException();
        }

        return new SteamProfile($result->response->players[0]);
    }
}