using System.Text;
using Guru.LitJson;
using UnityEngine;
using UnityEngine.Networking;

namespace Guru
{
	public class RefreshTokenRequest : RequestBase
	{
		protected override string RequestURL => IPMConfig.IPM_URL + "auth/api/v1/renewals/token";
		protected override UnityWebRequest CreateRequest()
		{
			var request = new UnityWebRequest(RequestURL, "POST");
			//request.uploadHandler = new UploadHandlerRaw();
			request.downloadHandler = new DownloadHandlerBuffer();
			request.SetRequestHeader(IPMConfig.Header_Param_ContentType, IPMConfig.Header_Value_ContentType);
			request.SetRequestHeader(IPMConfig.Header_Param_APPID, IPMConfig.IPM_X_APP_ID);
			request.SetRequestHeader(IPMConfig.Header_Param_UID, IPMConfig.IPM_UID);
			request.SetRequestHeader(IPMConfig.Header_Param_ACCESS_TOKEN, IPMConfig.IPM_TOKEN);
			return request;
		}

		protected override void RequestSuccessCallBack(string response)
		{
			ResponseData<TokenResponse> responseData =
				JsonUtility.FromJson<ResponseData<TokenResponse>>(response);
			
			this.Log(response);
			this.Log(responseData.data.ToString());
			IPMConfig.IPM_TOKEN = responseData.data.token;
			IPMConfig.IPM_TOKEN_TIME = TimeUtil.GetCurrentTimeStampSecond();
			this.Log($"[SDK] --- RefreshTokenRequest Success: {responseData.data.token}");
		}
	}
}