package jp.agentec.abook.abv.bl.repo;

import java.util.Locale;

import org.json.adf.JSONObject;

import jp.agentec.abook.abv.bl.acms.client.AcmsClient;
import jp.agentec.abook.abv.bl.acms.client.json.CmsUrlJSON;
import jp.agentec.abook.abv.bl.common.ABVEnvironment;
import jp.agentec.abook.abv.bl.common.Constant.ReaderConstant;
import jp.agentec.abook.abv.bl.common.exception.ABVExceptionCode;
import jp.agentec.abook.abv.bl.common.exception.AcmsException;
import jp.agentec.abook.abv.bl.common.exception.NetworkDisconnectedException;
import jp.agentec.abook.abv.bl.common.util.SecurityUtil;
import jp.agentec.adf.net.http.HttpResponse;


public class RepoClient {
	private static final String TAG = "RepoClient";
	
	private static RepoClient instance = null;

	public static RepoClient getInstance() {
		if (instance == null) {
			instance = new RepoClient();
		}
		
		return instance;
	}

	/**
	 * サーバ日付（UTC)を返す。
	 * 
	 * @param repositoryFqdn
	 * @return
	 * @throws AcmsException
	 * @throws NetworkDisconnectedException
	 */
	public String getServerDate(String repositoryFqdn) throws AcmsException, NetworkDisconnectedException {
		String getUrl = "https://" + repositoryFqdn + "/repo/getServerTime";
		HttpResponse response = AcmsClient.getInstance(ABVEnvironment.getInstance().networkAdapter).send(getUrl, "", null);
		if (response.httpResponseCode != 200) {
			throw new AcmsException(ABVExceptionCode.S_E_ACMS_0500, null);
		}
		
		JSONObject json = new JSONObject(response.httpResponseBody);
		return json.getString("presentTime");
	}

	public CmsUrlJSON getCmsUrl(String repositoryFqdn, int siteId, String urlPath) throws AcmsException, NetworkDisconnectedException {
		String keyForReader = SecurityUtil.getEncryptString(ReaderConstant.SHARED_SECRET_REPO, "" + System.currentTimeMillis(), true);
		String url = "https://" + repositoryFqdn + "/repo/getCmsUrl?key=" + keyForReader + "&siteId=" + siteId + "&urlPath=" + urlPath + "&language=" + Locale.getDefault().getLanguage();
		HttpResponse response = AcmsClient.getInstance(ABVEnvironment.getInstance().networkAdapter).send(url, "", null);
		if (response.httpResponseCode != 200) {
			throw new AcmsException(ABVExceptionCode.S_E_ACMS_0500, null);
		}
		
		return new CmsUrlJSON(response.httpResponseBody);
	}


}
