/*-
 * ~~~~~~licensing~~~~~~
 * test-producers
 * ==========
 * 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.base.objects.service.impl;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;

import com.google.gson.JsonObject;

import ru.entaxy.platform.base.objects.EntaxyObject;
import ru.entaxy.platform.base.support.JSONUtils;

public class TrackedEntaxyObject implements EntaxyObject {

	static public TrackedEntaxyObject create(BundleContext bundleContext, String objectId, String objectType) {
		return new TrackedEntaxyObject(bundleContext, objectId, objectType);
	}
	
	protected BundleContext bundleContext;
	
	protected String objectId;
	protected String objectType;
	protected String factoryId = "UNKNOWN";
	
	protected JsonObject configuration;
	
	protected BundleInfoImpl bundleInfoImpl;
	
	protected TrackedEntaxyObject(BundleContext bundleContext, String objectId, String objectType) {
		super();
		this.bundleContext = bundleContext;
		this.objectId = objectId;
		this.objectType = objectType;
	}

	@Override
	public String getObjectId() {
		return this.objectId;
	}

	@Override
	public String getObjectType() {
		return this.objectType;
	}

	@Override
	public String getFactoryId() {
		return this.factoryId;
	}

	@Override
	public BundleInfo getBundleInfo() {
		return this.bundleInfoImpl;
	}

	@Override
	public String getConfiguration() {
		return (this.configuration == null?"{}":this.configuration.toString());
	}

	public TrackedEntaxyObject bundle(Bundle bundleValue) {
		this.bundleInfoImpl = new BundleInfoImpl(bundleContext, bundleValue.getBundleId());
		return this;
	};
	
	public TrackedEntaxyObject configuration(String configurationValue) {
		
		try {
			this.configuration = JSONUtils.getJsonRootObject(configurationValue);
			if (this.configuration.has(EntaxyObject.FIELDS.FACTORY_ID))
				this.factoryId = this.configuration.get(EntaxyObject.FIELDS.FACTORY_ID).getAsString();
		} catch (Exception e) {
			
		}
		
		if (this.configuration == null)
			this.configuration = new JsonObject();
		
		return this;
	};
	
}
