<?php

namespace Vinteract\Auth;

use Exception;
use InvalidArgumentException;

use \ReallySimpleJWT\Token;

class JwtToken {
	
	private $iat;
	private $exp;
	private $iss;
	private $data;
	private $tokenString;
	
	private $secret;
	
	function __construct() {
		
		$this->setSecret(\Vinteract\Client::getJWTSecretKey());
		
	}
	
	public function setIat($iat) {
		$this->iat = $iat;
		return $this;
	}
	
	public function setExp($exp) {
		$this->exp = $exp;
		return $this;
	}
	
	public function setIss($iss) {
		$this->iss = $iss;
		return $this;
	}
	
	public function setData($data) {
		$this->data = $data;
		return $this;
	}
	
	private function setSecret($secret) {
		$this->secret = $secret;
		return $this;
	}
	
	public function getIat() {
		return $this->iat;
	}
	
	public function getExp() {
		return $this->exp;
	}
	
	public function getIss() {
		return $this->iss;
	}
	
	public function getData() {
		return $this->data;
	}
	
	private function getSecret() {
		return $this->secret;
	}
	
	public function generate() {
		$this->tokenString = Token::customPayload([
			"iat" => $this->getIat(),
			"exp" => $this->getExp(),
			"iss" => $this->getIss(),
			"data" => $this->getData(),
		], $this->getSecret());
		return $this;
	}
	
	public function getToken() {
		return $this->tokenString;
	}
	
	public static function validate($token) {
		return Token::validate($token, (new static)->getSecret());
	}
	
	public static function getHeader($token) {
		return Token::getHeader($token, (new static)->getSecret());
	}
	
	public static function getPayload($token) {
		return Token::getPayload($token, (new static)->getSecret());
	}
	
	public static function getPayloadData($token, $key) {
		
		// Variables
		
		$data = self::getPayload($token);
		
		// @assert $key is a non-empty string
		// @assert $data is a loopable array
		// @otherwise return $default value
		
		if (!is_string($key) || empty($key) || !count($data)) {
			return $default;
		}
		
		// @assert $key contains a dot notated string
		
		if (strpos($key, '.') !== false) {
			$keys = explode('.', $key);
			foreach ($keys as $innerKey) {
				// @assert $data[$innerKey] is available to continue
				// @otherwise return $default value
				if (!array_key_exists($innerKey, $data)) {
					return $default;
				}
				$data = $data[$innerKey];
			}
			return $data;
		}
		
		return array_key_exists($key, $data) ? $data[$key] : $default;
		
	}
	
}
