package fucoin;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import fucoin.actions.join.ServerActionJoin;
import fucoin.supervisor.SuperVisorImpl;
import fucoin.wallet.WalletImpl;

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


public class Main {

    private static int numberOfWallets = 2;

    private static ActorSystem cSystem;

    private static ActorRef cSuperVisorActor;

    private static List<ActorRef> cActiveActors = new ArrayList<>();

    static {
        //Load configuration from current directory or from resources directory of jar
        File file = new File("application.conf");
        Config config = ConfigFactory.parseFile(file);
        if (!file.exists()) {
            System.out.println("Load default application.conf");
            config = ConfigFactory.parseResources("application.conf");
        } else {
            System.out.println("Load local application.conf");
        }

        //Init System Actor System
        cSystem = ActorSystem.create("Core", config);
        cSuperVisorActor = cSystem.actorOf(SuperVisorImpl.props(), "SuperVisorImpl");
        System.out.print("Supervisor address: ");
        System.out.println(cSuperVisorActor.path().toStringWithAddress(cSystem.provider().getDefaultAddress()));
    }

    public static void main(String[] args) throws InterruptedException {
        createWallets();
    }

    private static void createWallets() {
        //Init Wallets
        for (int i = 0; i < numberOfWallets; i++) {
            String nameOfTheWallet = "Wallet" + String.valueOf(i);
            //chain the wallets. wallet2 knows wallet1, wallet3 knows wallet2 and so on.
            String nameOfThePreviousWallet = "";
            if (i > 0) {
                nameOfThePreviousWallet = "Wallet" + String.valueOf(i - 1);
            }
            Props props = WalletImpl.props(null, nameOfThePreviousWallet, nameOfTheWallet, cSuperVisorActor);
            ActorRef actorRef = cSystem.actorOf(props, nameOfTheWallet);
            cSuperVisorActor.tell(new ServerActionJoin(nameOfTheWallet), actorRef);
            cActiveActors.add(actorRef);
        }
    }
}