package love.distributedrebirth.no2all.zerofungus;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import love.distributedrebirth.no2all.react.nostr.client.NoStrRtsClient;
import love.distributedrebirth.no2all.react.nostr.server.NoStrRtsServer;
import love.distributedrebirth.no2all.react.nostr.server.relay.NoStrRtsServerRelay;
import love.distributedrebirth.no2all.react.nostr.server.relay.NoStrRtsServerRelaySubs;
import love.distributedrebirth.no2all.react.warp.No2AllReactWarpCore;
import love.distributedrebirth.no2all.react.warp.No2AllRtsWarpSpeedMonitor;
import love.distributedrebirth.no2all.react.wire.client.No2AllRtsClient;
import love.distributedrebirth.no2all.react.wire.server.No2AllRtsServer;
import love.distributedrebirth.no2all.react.wire.server.No2AllRtsServerLog;
import love.distributedrebirth.no2all.zerofungus.service.ZFunRtsConfigJetty;
import love.distributedrebirth.no2all.zerofungus.service.ZFunRtsConfigLogger;
//import ᒢᐩᐩ.ᔿᐤᒄʸ.ᣔᒃᣔᒼᓑᔆ.BãßBȍőnAbacusInstanceMBeanʸᴰ;
import love.distributedrebirth.no2all.zerofungus.service.ZFunRtsInitJdbc;

public enum ZeroFungus /* implements BãßBȍőnAbacusInstanceMBeanʸᴰ<ZeroFungus> */ {
	INSTANCE;

	private No2AllReactWarpCore foei = new No2AllReactWarpCore();
	private List<ZFunRtsConfigJetty> jetties = new ArrayList<>();

	public static void main(String[] args) {
		Iterator<String> arguments = Arrays.asList(args).iterator();
		boolean hasPort = arguments.hasNext() && arguments.next().equals("-p") && arguments.hasNext();
		
		// todo move
		new File("logs").mkdir();

		// config jetty
		INSTANCE.jetties.clear();
		if (hasPort) {
			// note: multiple currently does not work...
			INSTANCE.jetties.add(Arrays.asList(arguments.next().split(",")).stream().map(v -> Integer.parseInt(v)).findFirst().map(v -> new ZFunRtsConfigJetty(v)).get());
		} else {
			INSTANCE.jetties.add(new ZFunRtsConfigJetty(8080));
		}
		INSTANCE.start();
	}

	public void stop() {
		jetties.forEach(v -> v.stop());
		// foei.fire(No2AllReactWarpCore.DILITHIUM, new EjectWrapCoreShutdown());
	}

	public void start() {
		// setup logger + warp monitor
		foei.load(new ZFunRtsConfigLogger());
		foei.load(new No2AllRtsWarpSpeedMonitor());

		// add websocket wire support + log
		foei.load(new No2AllRtsClient());
		foei.load(new No2AllRtsServer());
		foei.load(new No2AllRtsServerLog());

		// add nostr support
		foei.load(new NoStrRtsClient());
		foei.load(new NoStrRtsServer());
		foei.load(new NoStrRtsServerRelay());
		foei.load(new NoStrRtsServerRelaySubs());

		// config zero fungus servers and clients
		foei.load(new ZFunRtsInitJdbc(foei));
		foei.load(new ZFunRtsServer());
		// foei.load(new ZFunRtsClientReplay());

		// load jetties and join
		jetties.forEach(v -> foei.load(v));
		foei.load(new ZFunRtsServerBooted());
		jetties.stream().findFirst().ifPresent(v -> v.join());
	}
}