/*-
 * ~~~~~~licensing~~~~~~
 * object-producer-api
 * ==========
 * Copyright (C) 2020 - 2022 EmDev LLC
 * ==========
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.platform.core.producer.api;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

public class EntaxyProducerUtils {

	protected static Gson sharedGson = new Gson();
	
	protected static class InstructionsItemBuilder {
		
		protected JsonObject instructionsJson;
		
		protected InstructionsItemBuilder(JsonObject jsonObject) {
			this.instructionsJson = jsonObject;
		}
		
	}
	
	public static class InstructionsBuilder extends InstructionsItemBuilder {

		protected InstructionsBuilder(JsonObject jsonObject) {
			super(jsonObject);
		}
		
		public CommandBuilder command(String commandName) {
			if (!instructionsJson.has(commandName))
				instructionsJson.add(commandName, new JsonObject());
			return new CommandBuilder(instructionsJson, instructionsJson.get(commandName).getAsJsonObject());

		}

		public CommandBuilder any() {
			return this.command("*");
		}	
		
		public JsonObject getInstructions() {
			return this.instructionsJson;
		}
		
		public String getInstructionsString() {
			return getInstructions().toString();
		}
	}
	
	public static class CommandBuilder extends InstructionsBuilder {

		protected JsonObject commandJson;
		
		protected CommandBuilder(JsonObject instructionsObject, JsonObject commandObject) {
			super(instructionsObject);
			commandJson = commandObject;
		}
		
		public CommandBuilder set(String name, Object value) {
			this.commandJson.remove(name);
			this.commandJson.add(name, sharedGson.toJsonTree(value));
			return this;
		}
		
	}
	
	public static InstructionsBuilder instructions() {
		return instructions(new JsonObject());
	}

	public static InstructionsBuilder instructions(JsonObject jsonObject) {
		return new InstructionsBuilder(jsonObject);
	}
}
