package com.uvigo.tMaestro.SCOCreator.templates;


import com.uvigo.mhp.*;
import java.awt.*;
import java.awt.event.*;
import org.havi.ui.*;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.BundleListener;
import org.osgi.framework.Filter;
import org.osgi.framework.FrameworkListener;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import com.uvigo.tMaestro.SCO.SCO;
//import com.uvigo.tMaestro.SCOCreator.tool.MainFrame;

public class demo extends Page implements SCO,Runnable {
    
    /**
     * Referencia al contexto proporcionado por el LMS
     * Se utilizar� para poder buscar el la API del LMS
     */
    private org.osgi.framework.BundleContext oContext;
    
    
    /**
     * Referencia a la escena sobre la que dibujar la plantilla
     */
    private HScene scene;
    
    /**
     * Referencia al hilo que har� todo el trabajo
     */
    private Thread oThread;
    
    /**
     * Indica si el SCO ha sido o no iniciado
     */
    private boolean bInit=false;
    
    /**
     * Variable que indica si el SCO es un bundle o no
     */
    private boolean bBundle=true;
    
    /**
     * Esta es la variable que apunta a la ventana en la que se lanza el SCO
     */
    private com.snaptwo.havi.ui.DBFrame oWindow;
    
    public demo() {
        if (java.beans.Beans.isDesignTime()) {
            try {
                initComponents();
                activeImage1.setContextManager(contextManager);
                activeImage1.setContext("incial");
                courseDelegate.setPage(this);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        courseDelegate = new com.uvigo.mhp.CourseDelegate();
        contextManager = new com.uvigo.mhp.ContextManager();
        hScrollPane1 = new com.uvigo.mhp.ui.HScrollPane();
        textPanel1 = new com.uvigo.mhp.textPanel.TextPanel();
        hScrollBar1 = new com.uvigo.mhp.ui.HScrollBar();
        activeImage1 = new com.uvigo.mhp.activeImage.ActiveImage();
        hImage1 = new com.uvigo.mhp.ui.HImage();

        courseDelegate.setPage(this);

        setLayout(null);

        setBackground(new java.awt.Color(153, 255, 153));
        setBackgroundImageMode(com.uvigo.mhp.ui.HPanel.IMAGE_DONT_SHOW);
        setBackgroundImageURL("");
        setName("HPage");
        setOpaque(true);
        hScrollPane1.setName("scrollPanel");
        hScrollPane1.setVerticalScrollControl(hScrollBar1);
        textPanel1.setConfigurationFile("templates/demo/texto.xml");
        textPanel1.setContext("inicial");
        textPanel1.setContextManager(contextManager);
        textPanel1.setName("textPanel");
        textPanel1.setOpaque(false);
        hScrollPane1.setViewportView(textPanel1);

        add(hScrollPane1);
        hScrollPane1.setBounds(60, 70, 470, 220);

        hScrollBar1.setName("scroollBar");
        hScrollBar1.setOrientation(org.havi.ui.HOrientable.ORIENT_TOP_TO_BOTTOM);
        add(hScrollBar1);
        hScrollBar1.setBounds(580, 130, 30, 90);

        activeImage1.setConfigurationFile("templates/demo/mundo.xml");
        activeImage1.setMouseEnabled(true);
        activeImage1.setName("activeImage");
        add(activeImage1);
        activeImage1.setBounds(60, 320, 470, 210);

        hImage1.setName("hImage");
        add(hImage1);
        hImage1.setBounds(60, 320, 470, 210);

    }// </editor-fold>//GEN-END:initComponents
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    public com.uvigo.mhp.activeImage.ActiveImage activeImage1;
    private com.uvigo.mhp.ContextManager contextManager;
    private com.uvigo.mhp.CourseDelegate courseDelegate;
    private com.uvigo.mhp.ui.HImage hImage1;
    private com.uvigo.mhp.ui.HScrollBar hScrollBar1;
    private com.uvigo.mhp.ui.HScrollPane hScrollPane1;
    private com.uvigo.mhp.textPanel.TextPanel textPanel1;
    // End of variables declaration//GEN-END:variables
    
    
    public static void main(String[] args) {
        try {
            demo oDemo = new demo();
            oDemo.bBundle=false;
            oDemo.install(new BundleContext() {
                public void addBundleListener(BundleListener bundleListener) {
                }
                public void addFrameworkListener(FrameworkListener frameworkListener) {
                }
                public void addServiceListener(ServiceListener serviceListener) {
                }
                public void addServiceListener(ServiceListener serviceListener, String string) throws InvalidSyntaxException {
                }
                public Filter createFilter(String string) throws InvalidSyntaxException {
                    return null;
                }
                public Bundle getBundle() {
                    return null;
                }
                public Bundle getBundle(long l) {
                    return null;
                }
                public Bundle[] getBundles() {
                    return null;
                }
                public java.io.File getDataFile(String string) {
                    return null;
                }
                public String getProperty(String string) {
                    return null;
                }
                public Object getService(ServiceReference serviceReference) {
                    return null;
                }
                public ServiceReference getServiceReference(String string) {
                    return null;
                }
                public ServiceReference[] getServiceReferences(String string, String string0) throws InvalidSyntaxException {
                    return null;
                }
                public Bundle installBundle(String string) throws BundleException {
                    return null;
                }
                public Bundle installBundle(String string, java.io.InputStream inputStream) throws BundleException {
                    return null;
                }
                public ServiceRegistration registerService(String string, Object object, java.util.Dictionary dictionary) {
                    return null;
                }
                public ServiceRegistration registerService(String[] string, Object object, java.util.Dictionary dictionary) {
                    return null;
                }
                public void removeBundleListener(BundleListener bundleListener) {
                }
                public void removeFrameworkListener(FrameworkListener frameworkListener) {
                }
                public void removeServiceListener(ServiceListener serviceListener) {
                }
                public boolean ungetService(ServiceReference serviceReference) {
                    return false;
                }
            });
            oDemo.start();
        } catch(Exception oE) {
            oE.printStackTrace();
            System.out.println("I CAN�T LAUNCH THIS SCO");
        }
    }
    
    /**
     * M�todo run para implementar la interfaz Runnable. Contiene el c�digo
     * a ejecutar.
     */
    public void run() {
        if (!bInit) {
            bInit = true;
            //Debemos obtener una escena para poder dibujar sobre ella
            HSceneFactory factory = HSceneFactory.getInstance();
            HSceneTemplate hst = new HSceneTemplate();
            hst.setPreference(
                    HSceneTemplate.SCENE_SCREEN_DIMENSION,
                    new org.havi.ui.HScreenDimension(1,1),
                    HSceneTemplate.REQUIRED);
            hst.setPreference(
                    HSceneTemplate.SCENE_SCREEN_LOCATION,
                    new org.havi.ui.HScreenPoint(0,0),
                    HSceneTemplate.REQUIRED);
            //Obtenemos la Escena
            scene = factory.getBestScene(hst);
            scene.setLayout(new BorderLayout());
              /*
               * Las librerias Havi que se proporcionan para la presentacion de este SCO simulan un entorno MHP en
               * un java.awt.Window Java que cuando es cerrado implica el cierre de la JVM, efecto no deseado.
               * Debemos cambiar el Window Listener por uno que implique destruir el SCO y no cerrar la JVM
               */
            try {
                oWindow = (com.snaptwo.havi.ui.DBFrame)scene.getParent().getParent().getParent();
                oWindow.setTitle("tMaestro SCO");
                final java.awt.event.WindowListener[] oListeners = oWindow.getWindowListeners();
                for (int i=0;i<oListeners.length;i++) oWindow.removeWindowListener(oListeners[i]);
                //Una vez eliminados los listener debemos crear el nuevo listener
                oWindow.addWindowListener(new java.awt.event.WindowListener() {
                    public void windowActivated(WindowEvent e) {
                        for (int i=0;i<oListeners.length;i++) oListeners[i].windowActivated(e);
                    }
                    public void windowClosed(WindowEvent e) {
                        
                    }
                    public void windowClosing(WindowEvent e) {
                        stop();
                    }
                    public void windowDeactivated(WindowEvent e) {
                        for (int i=0;i<oListeners.length;i++) oListeners[i].windowActivated(e);
                    }
                    public void windowDeiconified(WindowEvent e) {
                        for (int i=0;i<oListeners.length;i++) oListeners[i].windowActivated(e);
                    }
                    public void windowIconified(WindowEvent e) {
                        for (int i=0;i<oListeners.length;i++) oListeners[i].windowActivated(e);
                    }
                    public void windowOpened(WindowEvent e) {
                        for (int i=0;i<oListeners.length;i++) oListeners[i].windowActivated(e);
                    }
                });
                oWindow.setVisible(true);
            } catch(Exception oE) {
                oE.printStackTrace();
            }
            
            createAndShowTemplate();
        }
        
        
    }
    
    
    
    /*
     * METODOS DE COMUNICACION PARA EL LMS
     */
    
    public void start() {
        if (!bInit) {
            oThread = new Thread(this);
            oThread.setContextClassLoader(getClass().getClassLoader());
            oThread.start();
        }
    }
    
    public void stop() {
        //Cerramos el SCO
        if (bInit) {
            if (bBundle) {
                oWindow.setVisible(false);
                oWindow.dispose();
                oWindow = null;
                this.doDestroy();
                bInit = false;
            } else {
                //this.setVisible(false);
                //MainFrame.parent.setEnabled(true);
                //return;
                System.exit(0);
            }
        }
    }
    
    public void install(BundleContext oContext) {
        this.oContext=oContext;
    }
    
    public void uninstall() {
        stop();
    }
    
    private void createAndShowTemplate() {
        //Creamos la plantilla que se va a a�adir a la escena
        try {
            initComponents();
            activeImage1.setContextManager(contextManager);
            activeImage1.setContext("inicial");
            courseDelegate.setPage(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!java.beans.Beans.isDesignTime()) {
            com.uvigo.tMaestro.SCO.AutoConfigurer oConfigurer = new com.uvigo.tMaestro.SCO.AutoConfigurer();
            com.uvigo.tMaestro.SCO.Adaptation oAdaptation = new com.uvigo.tMaestro.SCO.Adaptation(oContext);
            oConfigurer.configure(this,oAdaptation.adapt());
        }
        
        scene.add(this);
        scene.validate();
        scene.setVisible(true);
        
        
    }
    
    
    private void doDestroy() {
        // Eleiminamos los elementos de la scena y la ocultamos
        scene.setVisible(false);
        scene.removeAll();
        
        // Eliminamos la scena
        HSceneFactory.getInstance().dispose(scene);
        scene = null;
    }
    
}
