/*-
 * ~~~~~~licensing~~~~~~
 * cluster-node-management
 * ==========
 * 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.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.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.node.ClusterLocalNodeDataProvider;
import ru.entaxy.esb.platform.core.management.node.LocalNodeMBean;
import ru.entaxy.esb.platform.core.management.node.NodeDataProvider;
import ru.entaxy.platform.base.support.CommonUtils;

@Services(requires = {
        @RequireService(ConfigurationAdmin.class),
        @RequireService(FeaturesService.class),
        @RequireService(HazelcastInstance.class),
        @RequireService(LocalNodeMBean.class)
	}
)
public class Activator extends BaseActivator implements MembershipListener {
	
	private HazelcastInstance hazelcastInstance;
	
	private LocalNodeMBean localNodeMBean;
	
	private Member localMember;
	
	private MemberMBeanManager memberMBeanManager;
	
	@Override
	protected void doStart() throws Exception {
        ConfigurationAdmin configurationAdmin = getTrackedService(ConfigurationAdmin.class);
        if (configurationAdmin == null)
            return;
        FeaturesService featuresService = getTrackedService(FeaturesService.class);
        if (featuresService == 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);
        initializeMBeans();
        
        hazelcastInstance.getCluster().addMembershipListener(this);

	}

	protected void fillMemberData() {
		NodeDataProvider dataProvider = localNodeMBean.getDataProvider();
		
		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())
				, 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()}));
	}

}
