/**
 * Copyright (c) 2000-2017 Liferay, Inc. All rights reserved.
 *
 * The contents of this file are subject to the terms of the Liferay Enterprise
 * pSubscription License ("License"). You may not use this file except in
 * compliance with the License. You can obtain a copy of the License by
 * contacting Liferay, Inc. See the License for the specific language governing
 * permissions and limitations under the License, including but not limited to
 * distribution rights of the Software.
 *
 *
 *
 */

package com.liferay.portal.kernel.license.messaging;

import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.messaging.Message;

/**
 * @author Igor Beslic
 */
public enum LicenseManagerMessageType {

	LCS_AVAILABLE, SUBSCRIPTION_VALID, VALIDATE_LCS, VALIDATE_SUBSCRIPTION;

	public static String MESSAGE_BUS_DESTINATION_REQUEST =
		"liferay/lcs_request";

	public static String MESSAGE_BUS_DESTINATION_STATUS = "liferay/lcs_status";

	public static JSONObject getMessagePayload(Message message) {
		return getMessagePayload(message.getPayload());
	}

	public static JSONObject getMessagePayload(Object object) {
		if (object instanceof String) {
			return getMessagePayload((String)object);
		}

		return null;
	}

	public static JSONObject getMessagePayload(String json) {
		try {
			JSONObject jsonObject = JSONFactoryUtil.createJSONObject(json);

			valueOf(jsonObject);

			return jsonObject;
		}
		catch (Exception e) {
			return null;
		}
	}

	public static LicenseManagerMessageType valueOf(JSONObject jsonObject) {
		String type = jsonObject.getString("type");

		return valueOf(type);
	}

	public Message createMessage() {
		Message message = new Message();

		message.setDestinationName(getDestinationName());

		JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

		jsonObject.put("type", name());

		message.setPayload(jsonObject.toString());

		return message;
	}

	public Message createMessage(LCSPortletState lcsPortletState) {
		Message message = new Message();

		message.setDestinationName(getDestinationName());

		JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

		jsonObject.put("state", lcsPortletState.intValue());
		jsonObject.put("type", name());

		message.setPayload(jsonObject.toString());

		return message;
	}

	public String getDestinationName() {
		if ((this == LCS_AVAILABLE) || (this == SUBSCRIPTION_VALID)) {
			return MESSAGE_BUS_DESTINATION_STATUS;
		}
		else if ((this == VALIDATE_LCS) || (this == VALIDATE_SUBSCRIPTION)) {
			return MESSAGE_BUS_DESTINATION_REQUEST;
		}

		return null;
	}

}