/*
 * Copyright 2016-2017 Leon Chen
 *
 * 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.
 */

package cn.nextop.gadget.core.message.jgroups;

import org.jgroups.JChannel;
import org.jgroups.Receiver;
import org.jgroups.View;
import org.jgroups.conf.ClassConfigurator;
import org.jgroups.util.Util;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Baoyi Chen
 */
public class MainInProcess {
	private static final int NODE_COUNT = 10;
	private List<JChannel> channels=new ArrayList<>(NODE_COUNT+1);

	static {
		ClassConfigurator.addProtocol((short) 1024, FilePing.class);
	}

	public static void main(String[] args) throws Exception {
		new MainInProcess().start();
	}

	public void start() throws Exception {
		// Clean up previous cluster files
		Files.list(Path.of("/Users/bela/tmp/jgroups/MyTestCluster")).forEach(path -> {
			try {
				boolean deleted=Files.deleteIfExists(path);
				if(deleted)
					System.out.printf("-- deleted %s\n", path);
			} catch (IOException e) {
				e.printStackTrace();
			}
		});
		
		for (int i = 0; i < NODE_COUNT; i++) {
			String nodeName = String.valueOf(i+1);
			final JChannel ch=new JChannel("jgroups-custom.xml").name(nodeName);
			ch.setReceiver(new Receiver() {
				@Override
				public void viewAccepted(View new_view) {
					System.out.println("[" + ch.getAddress() + "] View: " + new_view);
				}
			});
			channels.add(ch);
			ch.connect("MyTestCluster");
			// Thread.sleep(100);
		}
		
		Thread.sleep(1000);
		
		// kill Node-1 and create Node-11
		System.out.println("\n\n**** Killing Node-1 (simulating kill -9)...");
		stop(0);
		JChannel joiner=new JChannel("jgroups-custom.xml").name("11");
		channels.add(joiner);
		System.out.println("\n**** Starting node 11:");
		joiner.connect("MyTestCluster");
		Util.waitUntilAllChannelsHaveSameView(600_000, 1000, channels);
		System.out.printf("\n\n*** SUCCESS: the views are:\n%s\n\n", channels.stream()
		.map(ch -> String.format("%s: %s", ch.getAddress(), ch.view())).collect(Collectors.joining("\n")));
		Util.closeReverse(channels.toArray(new JChannel[]{}));
	}


	
	private void stop(int i) throws Exception {
		JChannel ch=channels.getFirst();
		Util.shutdown(ch);
		channels.removeFirst();
	}
	

}
