package com.sys.service;

import com.cku.core.ZAErrorCode;
import com.cku.util.Debugger;
import com.cku.util.HttpClientUtil;
import com.cku.util.HttpResult;
import com.cku.util.SysConfig;

import net.sf.json.JSONObject;

public class TokenService
{
	private static TokenService s_service = new TokenService();
	
	public static TokenService instance()
	{
		return s_service;
	}
	
	public long verifyTokenUser(String token) throws Exception
	{
		String sessionSrvUrl = SysConfig.getInstance().getProperty("session_server_url");
		HttpResult hr = HttpClientUtil.get(null, sessionSrvUrl + "/session?token=" + token, null);
		
		Debugger.doAssert(hr.getResultCode() == 200, ZAErrorCode.ZA_ERC_INVALID_STATUS, "%s", hr.getResponseBody());
		
		JSONObject jo = JSONObject.fromObject(hr.getResponseBody());
		long rc = jo.getLong("rc");
		
		Debugger.doAssert(rc == 0, ZAErrorCode.ZA_ERC_INVALID_STATUS, jo.getString("msg"));
		long userId = jo.getLong("userId");
		
		return userId;
	}
	
	public void invalidToken(String token) throws Exception
	{
		String sessionSrvUrl = SysConfig.getInstance().getProperty("session_server_url");
		HttpResult hr = HttpClientUtil.delete(null, sessionSrvUrl + "/session?token=" + token, null);
		
		Debugger.doAssert(hr.getResultCode() == 200, ZAErrorCode.ZA_ERC_INVALID_STATUS, "%s", hr.getResponseBody());
		
		JSONObject jo = JSONObject.fromObject(hr.getResponseBody());
		long rc = jo.getLong("rc");
		
		Debugger.doAssert(rc == 0, ZAErrorCode.ZA_ERC_INVALID_STATUS, jo.getString("msg"));
	}

	public String registerToken(Long userId) throws Exception
	{
		String sessionSrvUrl = SysConfig.getInstance().getProperty("session_server_url");
		HttpResult hr = HttpClientUtil.post(null, sessionSrvUrl + "/session?userId=" + userId, null);
		
		Debugger.doAssert(hr.getResultCode() == 200, ZAErrorCode.ZA_ERC_INVALID_STATUS, "%s", hr.getResponseBody());
		
		JSONObject jo = JSONObject.fromObject(hr.getResponseBody());
		long rc = jo.getLong("rc");
		
		Debugger.doAssert(rc == 0, ZAErrorCode.ZA_ERC_INVALID_STATUS, jo.getString("msg"));
		String token = jo.getString("token");
		
		return token;
	}
}
