<?php
/**
 * Created by PhpStorm.
 * User: brian
 * Date: 5/14/19
 * Time: 10:03 AM
 */

namespace Hilco;

use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
use League\OAuth2\Client\Provider\GenericProvider;
use League\OAuth2\Client\Token\AccessToken;

class M3Helper
{
    protected $activeToken;
    
    public function __construct()
    {
        $this->activeToken = null;
        $this->loadActiveToken();
    }
    
    protected function loadActiveToken(){
        $this->activeToken = false;
        $token = null;

        if(file_exists(storage_path('oauth2/token.txt'))){
            $token = new AccessToken(json_decode(file_get_contents(storage_path('oauth2/token.txt')), true));
        }
        if(is_null($token) || $token->getExpires() < time()){
            $token = $this->getAccessToken();
        }

        $this->activeToken = $token;
    }

    public function getAccessToken()
    {
        $provider = new GenericProvider(config('m3-config.clientCredentials'));
        try {
            $token = $provider->getAccessToken('password', config('m3-config.userCredentials'));
            $file = fopen(storage_path('oauth2/token.txt'), 'w');
            fwrite($file, json_encode($token));
            fclose($file);
        } catch (IdentityProviderException $e) {
            return $e->getMessage();
        }
        return $token;
    }

    public function activeToken(){
        return $this->activeToken;
    }

}