/*-
 * ~~~~~~licensing~~~~~~
 * management-core
 * ==========
 * Copyright (C) 2020 - 2021 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.esb.platform.base.management.core;

import java.util.LinkedHashMap;
import java.util.Map;

import ru.entaxy.platform.base.support.CommonUtils;

public class Qualifier {

	protected String domain = ManagementCore.ENTAXY_JMX_DOMAIN;
	
	protected Qualifier parent;

	protected Map<String, String> attributes = new LinkedHashMap<>();
	
	public Qualifier() {
		super();
	}

	public Qualifier(String key, String value) {
		super();
		attributes.put(key, value);
	}
	
	public Qualifier(Qualifier parent) {
		this();
		this.parent = parent;
	}
	
	public Qualifier qualifier(String key, String value) {
		return (new Qualifier(this)).attribute(key, value);
	}

	public Qualifier attribute(String key, String value) {
		this.attributes.put(key, value);
		return this;
	}
	
	public String getDomain() {
		if (this.parent == null)
			return CommonUtils.getValid(this.domain, ManagementCore.ENTAXY_JMX_DOMAIN);
		else
			return parent.getDomain();
	}
	
	public String getAttributes() {
		String value = this.parent==null?"":this.parent.getAttributes();
		for (Map.Entry<String, String> entry: this.attributes.entrySet()) {
			if (!value.isEmpty()) {
				value += ",";
			}
			value += entry.getKey() + "=" + entry.getValue();
		}
		return value;
	}
	
	public String getValue() {
		String value = getAttributes();
		if (value.isEmpty())
			return getDomain();
		else
			return getDomain() + ":" + value;
	}
	
	public String getFullString() {
		return ManagementCore.JMX_OBJECTNAME + "=" + getValue();
	}
}
