package org.bdware.sc.server;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.doip.endpoint.server.DoipListenerConfig;
import org.bdware.doip.endpoint.server.DoipServerImpl;
import org.bdware.doip.endpoint.server.DoipServiceInfo;
import org.bdware.sc.handler.DOOPRequestHandler;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class DoipLocalSingleton {
    static Logger LOGGER = LogManager.getLogger(DoipLocalSingleton.class);

    public static void main(String[] arg) throws InterruptedException {
        final int port = (arg.length == 0 ? 21042 : Integer.parseInt(arg[0]));

        Thread doipServerThread = new Thread(){
            @Override
            public void run() {
                try {
                    DoipLocalSingleton.run(port);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        doipServerThread.start();
    }

    public static void run(int port) throws InterruptedException {
        List<DoipListenerConfig> infos = new ArrayList<>();
        try {
            infos.add(new DoipListenerConfig("tcp://127.0.0.1:" + port, "2.1"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        DoipServiceInfo info = new DoipServiceInfo("aibd.govdata.tj/do.3f9c41e6-9f8e-48a0-9220-53f438d40e43", "ownerDEF", "gateRepo", infos);
        DoipServerImpl server = new DoipServerImpl(info);
        final AtomicInteger count = new AtomicInteger(0);
        DOOPRequestHandler handler = DOOPRequestHandler.createHandler();
        server.setRepositoryHandler(handler);
        server.start();
        for (; ; ) {
            LOGGER.info("Count:" + count.get());
            Thread.sleep(10000);
        }
    }

    public static void run(String doipAddr) throws InterruptedException {
        List<DoipListenerConfig> infos = new ArrayList<>();
        try {
            infos.add(new DoipListenerConfig(doipAddr, "2.1"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        DoipServiceInfo info = new DoipServiceInfo("aibd.govdata.tj/do.3f9c41e6-9f8e-48a0-9220-53f438d40e43", "ownerDEF", "gateRepo", infos);
        DoipServerImpl server = new DoipServerImpl(info);
        final AtomicInteger count = new AtomicInteger(0);
        DOOPRequestHandler handler = DOOPRequestHandler.createHandler();
        server.setRepositoryHandler(handler);
        server.start();
        for (; ; ) {
            LOGGER.info("Count:" + count.get());
            Thread.sleep(10000);
        }
    }
}
