package mimis;

import java.util.ArrayList;
import java.util.ServiceLoader;

import javax.swing.UIManager;

import mimis.application.Application;
import mimis.device.Device;
import mimis.exception.worker.ActivateException;
import mimis.exception.worker.DeactivateException;
import mimis.input.Task;
import mimis.manager.ButtonManager;
import mimis.manager.CurrentButtonManager;
import mimis.value.Action;
import mimis.worker.Component;

public class Main extends Mimis {
    protected CurrentButtonManager applicationManager;
    protected ButtonManager deviceManager;
    protected Gui gui;

    static {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {}
        
    }

    public static Component[] getApplications() {
    	ArrayList<Component> componentList = new ArrayList<Component>();
    	for (Application application : ServiceLoader.load(mimis.application.Application.class)) {
    		if (application instanceof Component) {
    			componentList.add((Component) application);
    		}
    	}
    	return componentList.toArray(new Component[]{});
    }

    public static Component[] getDevices() {
    	ArrayList<Component> componentList = new ArrayList<Component>();
    	for (Device device : ServiceLoader.load(mimis.device.Device.class)) {
    		if (device instanceof Component) {
    			componentList.add((Component) device);
    		}
    	}
    	return componentList.toArray(new Component[]{});
    }

    public Main() {
        super(getApplications());

        /* Create gui from application and device managers */
        applicationManager = new CurrentButtonManager(router, componentCycle, "Applications", currentArray);
        deviceManager = new ButtonManager("Devices", initialize(false, getDevices()));
        gui = new Gui(this, applicationManager, deviceManager);
        manager.add(initialize(false, gui));
    }

    public void activate() throws ActivateException {
        super.activate();
        listen(Task.class);

        /* Start managers */
        applicationManager.start();
        deviceManager.start();

        /* Force display of current component when gui started */
        gui.start();
        while (!gui.active());
        end(Action.CURRENT);
    }

    protected void deactivate() throws DeactivateException {
        super.deactivate();

        log.debug("Stop managers");
        applicationManager.stop();
        deviceManager.stop();
    }

    public void exit() {
        super.exit();

        log.debug("Exit managers");
        applicationManager.exit();
        deviceManager.exit();
    }

    public void end(Action action) {
        super.end(action);
        switch (action) {
            case CURRENT:
            case NEXT:
            case PREVIOUS:
                applicationManager.currentChanged();
                break;
        }
    }

    public static void main(String[] args) {
        new Main().start(false);
    }
}
