/*-
 * ~~~~~~licensing~~~~~~
 * cluster-node-management
 * ==========
 * Copyright (C) 2020 - 2025 EmDev LLC
 * ==========
 * You may not use this file except in accordance with the License Terms of the Copyright
 * Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
 * rights to the Software and any copies are the property of the Copyright Holder. Unless
 * it is explicitly allowed the Copyright Holder, the User is prohibited from using the
 * Software for commercial purposes to provide services to third parties.
 * 
 * The Copyright Holder hereby declares that the Software is provided on an "AS IS".
 * Under no circumstances does the Copyright Holder guarantee or promise that the
 * Software provided by him will be suitable or not suitable for the specific purposes
 * of the User, that the Software will meet all commercial and personal subjective
 * expectations of the User, that the Software will work properly, without technical
 * errors, quickly and uninterruptedly.
 * 
 * Under no circumstances shall the Copyright Holder or its Affiliates is not liable
 * to the User for any direct or indirect losses of the User, his expenses or actual
 * damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
 * or damage to data, property, etc.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.esb.platform.core.management.cluster.node.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;

import org.apache.karaf.cellar.core.ClusterManager;
import org.apache.karaf.cellar.core.command.ExecutionContext;
import org.apache.karaf.features.FeaturesService;
import org.apache.karaf.util.tracker.BaseActivator;
import org.apache.karaf.util.tracker.annotation.RequireService;
import org.apache.karaf.util.tracker.annotation.Services;
import org.osgi.service.cm.ConfigurationAdmin;

import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.Member;
import com.hazelcast.core.MemberAttributeEvent;
import com.hazelcast.core.MembershipEvent;
import com.hazelcast.core.MembershipListener;

import ru.entaxy.esb.platform.core.management.cluster.node.Attributes;
import ru.entaxy.esb.platform.core.management.cluster.node.ClusterUtils;
import ru.entaxy.esb.platform.core.management.node.ClusterLocalNodeDataProvider;
import ru.entaxy.esb.platform.core.management.node.LocalNodeMBean;
import ru.entaxy.esb.platform.core.management.node.NodeDataProvider;

@Services(requires = {
        @RequireService(ConfigurationAdmin.class),
        @RequireService(FeaturesService.class),
        @RequireService(HazelcastInstance.class),
        @RequireService(LocalNodeMBean.class),
        @RequireService(ClusterManager.class),
        @RequireService(ExecutionContext.class)
	}
)
public class Activator extends BaseActivator implements MembershipListener {
	
	private HazelcastInstance hazelcastInstance;
	
	private LocalNodeMBean localNodeMBean;
	
	private Member localMember;
	
	private MemberMBeanManager memberMBeanManager;
	
	private ServiceHelper serviceHelper;
	
	@Override
	protected void doStart() throws Exception {
        ConfigurationAdmin configurationAdmin = getTrackedService(ConfigurationAdmin.class);
        if (configurationAdmin == null)
            return;
        FeaturesService featuresService = getTrackedService(FeaturesService.class);
        if (featuresService == null)
            return;
        
        serviceHelper = new ServiceHelper();
        
        serviceHelper.clusterManager = getTrackedService(ClusterManager.class);
        if (serviceHelper.clusterManager == null)
        	return;
        
        serviceHelper.executionContext = getTrackedService(ExecutionContext.class);
        if (serviceHelper.executionContext == null)
        	return;
        
        localNodeMBean = getTrackedService(LocalNodeMBean.class);
        if (localNodeMBean == null)
        	return;
        
        hazelcastInstance = getTrackedService(HazelcastInstance.class);
        if (hazelcastInstance == null)
            return; 

        localMember = hazelcastInstance.getCluster().getLocalMember();
        fillMemberData();
        registerDataProvider();
        
        memberMBeanManager = new MemberMBeanManager(bundleContext, serviceHelper);
        initializeMBeans();
        
        hazelcastInstance.getCluster().addMembershipListener(this);

	}

	protected void fillMemberData() {
		NodeDataProvider dataProvider = localNodeMBean.getDataProvider();

		localMember.setStringAttribute(Attributes.CELLAR_NODE_ID, ClusterUtils.getCellarNodeId(localMember));
		
		localMember.setStringAttribute(Attributes.ENTAXY_PLATFORM_VERSION, dataProvider.getEntaxyPlatformVersion());
		localMember.setStringAttribute(Attributes.HTTP_PORT, dataProvider.getHttpPort());
		localMember.setStringAttribute(Attributes.SSH_PORT, dataProvider.getSshPort());
		localMember.setBooleanAttribute(Attributes.UI_ENABLED, dataProvider.isUIEnabled());
		
	}

    
	protected void registerDataProvider() {
		bundleContext.registerService(ClusterLocalNodeDataProvider.class
				, new ClusterLocalNodeDataProviderImpl(localMember, localNodeMBean.getDataProvider(), serviceHelper)
				, new Hashtable<>());
	}
	
	protected void initializeMBeans() {
		List<Member> members = new ArrayList<>(hazelcastInstance.getCluster().getMembers());
		members.remove(localMember);
		if (members.size() > 0)
			memberMBeanManager.added(members);
		
	}
	
	@Override
	public void memberAdded(MembershipEvent membershipEvent) {
		if (membershipEvent.getMember() != localMember)
			memberMBeanManager.added(Arrays.asList(new Member[] {membershipEvent.getMember()}));
	}

	@Override
	public void memberRemoved(MembershipEvent membershipEvent) {
		if (membershipEvent.getMember() != localMember)
			memberMBeanManager.removed(Arrays.asList(new Member[] {membershipEvent.getMember()}));
	}

	@Override
	public void memberAttributeChanged(MemberAttributeEvent memberAttributeEvent) {
		if (memberAttributeEvent.getMember() != localMember)
			memberMBeanManager.modified(Arrays.asList(new Member[] {memberAttributeEvent.getMember()}));
	}

}
