package ld5_34;

import jade.gui.GuiAgent;
import jade.gui.GuiEvent;
import jade.wrapper.AgentController;
import jade.wrapper.ContainerController;

import java.util.ArrayList;
import java.util.List;

public class GuiLauncher extends GuiAgent {
    private void print(String data, String elgesenosId) {
        if (elgesenosId != null) {
            System.out.println("A[" + getLocalName() + " | " + elgesenosId + "] " + data);
        } else {
            System.out.println("A[" + getLocalName() + "] " + data);
        }
    }
    private GuiLauncherGUI myGui;
    private List<String> createdAgents = new ArrayList<>();

    protected void setup() {
        myGui = new GuiLauncherGUI(this);
        System.out.println("GuiLauncher paruoštas.");
    }

    @Override
    protected void onGuiEvent(GuiEvent ev) {
        int type = ev.getType();
        String agentClass = (String) ev.getParameter(0);
        String agentName = (String) ev.getParameter(1);
        ContainerController cc = getContainerController();

        try {
            if (type == 1) {
                AgentController ac = cc.createNewAgent(agentName, agentClass, null);
                ac.start();
                createdAgents.add(agentName);
                myGui.updateStatus("Agent was started: " + agentName);
            } 
            else if (type == 2) {
                cc.getAgent(agentName).kill();
                createdAgents.remove(agentName);
                myGui.updateStatus("Agent destroyed: " + agentName);
            } 
            else if (type == 3) {
                myGui.updateStatus("All agents are getting ended...");
                
                for (String name : createdAgents) {
                    try {
                        cc.getAgent(name).kill();
                        print("Sunaikintas: " + name,null);
                    } catch (Exception e) {
                        print("Error Dstroying agent", null);
                    }
                }
                createdAgents.clear();
                
                myGui.updateStatus("Done");
                doDelete();
            }
        } catch (Exception e) {
            myGui.updateStatus("Error: " + e.getMessage());
        }
    }

    protected void takeDown() {
        if (myGui != null) myGui.dispose();
        print("Getting killed", null);
    }
}