<?php

namespace App\Classes\Modules\Unity\Services;

use Config;
use Cache;
use Illuminate\Support\Facades\Http;

class GetAccessToken
{
    private $getAccessTokenEndpoint;

    private $username;

    private $password;

    private $apiKey;

    private $cacheName;

    private $cacheTime;

    private $accessToken;

    public function __construct()
    {
        $this->getAccessTokenEndpoint = Config::get('unity.url').Config::get('unity.endpoint.login');
        $this->username = Config::get('unity.auth.login.username');
        $this->password = Config::get('unity.auth.login.password');
        $this->apiKey = Config::get('unity.auth.api_key.key');
        $this->cacheName = 'unity_access_token';
        $this->cacheTime = Config::get('unity.access_token_cache');
        $this->accessToken = "";
    }

    public function execute(){

        if(!empty($this->getCachedAccessToken())) return $this->getCachedAccessToken();

        if(empty($this->apiKey)){
            $response = Http::post($this->getAccessTokenEndpoint, [
                'email' => $this->username,
                'password' => $this->password ,
            ])->object();
            $this->accessToken = $response->access_token;
        }else{
            $this->accessToken = $this->apiKey;
        }

        $this->cacheAccessToken();

        //TODO: Throw error if access token not available

        return  $this->accessToken;
    }

    private function getCachedAccessToken(){
        return Cache::store('file')->get($this->cacheName);
    }

    private function cacheAccessToken(){
        Cache::store('file')->put($this->cacheName, $this->accessToken, $this->cacheTime);
    }
}
