package tmaestroplayer;

import edutainmentclient.Main;
import java.awt.Color;
import java.awt.DisplayMode;
import java.awt.GraphicsDevice;
import java.awt.GridBagConstraints;
import java.awt.Window;
import java.awt.event.KeyEvent;
import java.beans.PropertyVetoException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.media.EndOfMediaEvent;
import javax.media.Player;
import javax.media.StartEvent;
import javax.media.StopEvent;
import javax.media.Time;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.KeyStroke;
import tmaestroplayer.actions.KeyboardAction;

/**
 *
 * @author Silvia
 */
public class MainWindow extends JFrame implements ControllerListener {

    private static MainWindow instance;
    public JDesktopPane panel;
    //protected GraphicalLoginFrame oGLF;
    protected CourseLoader oCL;
    protected String rutaScorm;
    protected String nombreCurso;
    protected String userName;
    protected String courseId;
    public String scoId = "";
    protected String courseURL;
    protected String scoPath = "";
    protected String scoTimestamp = "";
    protected String option = "Op 1.xml";
    protected String fullScreen = "true";
    public Player bgMusicPlayer;
    public boolean forzarInicio;

    public MainWindow(boolean forzarInicio) {
        super("TMaestro Player");
        System.out.println("Entor en MainWindow()");
        this.forzarInicio = forzarInicio;
    }

    public MainWindow(String userId, boolean forzarInicio) {
        super("TMaestro Player");
        System.out.println("Entor en MainWindow(userId)");
        this.userName = userId;
        this.forzarInicio = forzarInicio;
    }

    public MainWindow(String userId, String courseURL, String courseId, String scoId, String scoPath, String scoTimestamp, boolean forzarInicio) {
        super("TMaestro Player");
        System.out.println("Entor en MainWindow(userId, courseURL, courseId, scoId, scoPath, scoTimestamp, boolean)");
        this.userName = userId;
        this.courseId = courseId;
        this.courseURL = courseURL;
        this.scoId = scoId;
        this.scoPath = scoPath;
        this.scoTimestamp = scoTimestamp;
        this.forzarInicio = forzarInicio;
    }

    public String getOption(String rutaScorm, String optionS) {


        String rutaOptions = rutaScorm + "OPTIONS/";


        URL url = null;
        try {
            optionS = optionS.replace(" ", "%20");
            System.out.println("rutaScormmmmmmmmm " + rutaScorm + optionS);
            url = new URL(rutaOptions + optionS);
        } catch (MalformedURLException ex) {
            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            URLConnection urlC = url.openConnection();
        } catch (IOException ex) {
            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            InputStream is = url.openStream();
        } catch (IOException ex) {
            System.out.println("No existe la opcion " + optionS);

            try {
                System.out.println("rutaScormmmmmmmmm " + rutaScorm + "Op%201.xml");
                url = new URL(rutaOptions + "Op%201.xml");
            } catch (MalformedURLException ex1) {
                Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex1);
            }
            try {
                URLConnection urlC = url.openConnection();
            } catch (IOException ex1) {
                Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex1);
            }
            try {
                InputStream is = url.openStream();
            } catch (IOException ex1) {
                System.out.println("No existe la opcion Op 1.xml");
                try {
                    System.out.println("rutaScormmmmmmmmm " + rutaScorm + "Op%202.xml");
                    url = new URL(rutaOptions + "Op%202.xml");
                } catch (MalformedURLException ex2) {
                    Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex2);
                }
                try {
                    URLConnection urlC = url.openConnection();
                } catch (IOException ex2) {
                    Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex2);
                }
                try {
                    InputStream is = url.openStream();
                } catch (IOException ex2) {
                    System.out.println("No existe la opcion Op 2.xml");
                    try {
                        System.out.println("rutaScormmmmmmmmm " + rutaScorm + "op1.xml");
                        url = new URL(rutaOptions + "op1");
                    } catch (MalformedURLException ex3) {
                        Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex3);
                    }
                    try {
                        URLConnection urlC = url.openConnection();
                    } catch (IOException ex3) {
                        Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex3);
                    }
                    try {
                        InputStream is = url.openStream();
                    } catch (IOException ex3) {
                        System.out.println("No existe la opcion op1.xml");
                        try {
                            System.out.println("rutaScormmmmmmmmm " + rutaScorm + "op2.xml");
                            url = new URL(rutaOptions + "op2.xml");
                        } catch (MalformedURLException ex4) {
                            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex4);
                        }
                        try {
                            URLConnection urlC = url.openConnection();
                        } catch (IOException ex4) {
                            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex4);
                        }
                        try {
                            InputStream is = url.openStream();
                        } catch (IOException ex4) {
                            System.out.println("No existe la op2.xml");
                            System.out.println("Mal puesta la opcion joderrrrrrrrrrrrrrrrrrr");
                            return null;
                        }
                        return "op2.xml";
                    }
                    return "op1.xml";
                }
                return "Op 2.xml";
            }
            return "Op 1.xml";
        }
        System.out.println("la opcion puesta en el fichero de configuración");
        return optionS;
    }

    public void init() {

        //String FICHERO_CONFIGURACION = System.getProperty("user.dir") + File.separator + "config" + File.separator + "tmaestroplayer" + File.separator + "options.properties";
        //System.out.println("Fichero de configuración " + FICHERO_CONFIGURACION);
        InputStream is = null;

            //is = new FileInputStream(new File(FICHERO_CONFIGURACION));
            //prop.load(is);
             is = Main.class.getResourceAsStream("/config/options.properties");

        Properties options = new Properties();

        try {
            options.load(is);
            //Leemos la configuracion del fichero
            //options.load( MainWindow.class.getResourceAsStream("/tmaestroplayer/config/options.properties"));

        } catch (IOException ex) {
            ex.printStackTrace();

        }

        if (Main.rutascorm != null) {
            rutaScorm = Main.rutascorm;////options.getProperty("rutascorm");
            nombreCurso = Main.nombrecurso;//options.getProperty("nombrecurso");

        } 

        option = options.getProperty("option");
        fullScreen = options.getProperty("fullscreen");

        this.setUndecorated(true);

        this.setLayout(null);
        //this.setBounds((1280-800)/2, (1024-800)/2, 800, 600);

        this.setBounds(0, 0, 720, 576);

        JLabel jLabelBackgroundTop = new JLabel();
        jLabelBackgroundTop.setBackground(Color.BLACK);
        jLabelBackgroundTop.setOpaque(true);
        jLabelBackgroundTop.setBounds(0, 0, 800, 12);
        jLabelBackgroundTop.setBounds(0, 0, 7, 12);

        JLabel jLabelBackgroundBottom = new JLabel();
        jLabelBackgroundBottom.setBackground(Color.BLACK);
        jLabelBackgroundBottom.setOpaque(true);
        jLabelBackgroundBottom.setBounds(0, 588, 800, 12);

        JLabel jLabelBackgroundLeft = new JLabel();
        jLabelBackgroundLeft.setBackground(Color.BLACK);
        jLabelBackgroundLeft.setOpaque(true);
        jLabelBackgroundLeft.setBounds(0, 0, 40, 600);

        JLabel jLabelBackgroundRight = new JLabel();
        jLabelBackgroundRight.setBackground(Color.BLACK);
        jLabelBackgroundRight.setOpaque(true);
        jLabelBackgroundRight.setBounds(760, 0, 40, 600);
        /*
        add(jLabelBackgroundTop);
        add(jLabelBackgroundBottom);
        add(jLabelBackgroundLeft);
        add(jLabelBackgroundRight);
         */
        //instance.oGLF = new GraphicalLoginFrame(instance);
        //instance.panel = (JDesktopPane) instance.oGLF.getVisual();


        oCL = new CourseLoader(this);
        panel = (JDesktopPane) oCL.getVisual();

        panel.setBounds(0, 0 / 2, 720, 576);
        //panel.setBounds((800 - 720) / 2, (600 - 576) / 2, 720, 576);
        panel.setVisible(true);

        add(panel);

        this.registerKeyboardActions();

        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        //this.setVisible(true);


        //Para pantalla completa
        if (fullScreen.equals("true")) {
            GraphicsDevice myDevice = java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
            if (myDevice.isFullScreenSupported()) {

                System.out.println("Soporta pantalla completa");

                myDevice.setFullScreenWindow(this);

                myDevice.setDisplayMode(new DisplayMode(800, 600, 32, 60));

            } else {
                System.out.println("No soporta pantalla completa");
            }
        }

        //panel.setSelectedFrame(oCL.vsu);

        if (!oCL.restored) {
            panel.setSelectedFrame(oCL.vsu);

        } else {
            System.out.println("¬¬¬¬¬¬¬¬¬¬¬¬ Restaurado un estado previo");

        }

        requestFocus();

        this.setVisible(true);

        this.setExtendedState(ICONIFIED);

        this.setExtendedState(NORMAL);

        panel.requestFocusInWindow();
        //panel.requestFocus();
        //panel.getDesktopManager().activateFrame(oCL.vsu);


        //this.toFront();
        //this.repaint();
        //requestFocus();

        //this.setAlwaysOnTop(true);
        //this.setAlwaysOnTop(false);

        JInternalFrame selectedJif = panel.getSelectedFrame();

        if (selectedJif instanceof VentanaSeleccionUnidad) {
            System.out.println("@@@@@@@@@@@" + ((VentanaSeleccionUnidad) selectedJif).unidadPrincipal.getIdentifier());

        } else if (selectedJif instanceof VentanaSCO) {
            System.out.println("@@@@@@@@@@" + ((VentanaSCO) selectedJif).getAtcx().nameSCO);

        } else if (selectedJif instanceof VentanaSeleccionCurso) {
            System.out.println("@@@@@@@@ La JIF seleccionada es de seleccion de curso");

        } else {
            System.out.println("@@@@@@@@ La JIF seleccionada no es ni vsu ni vsco");

        }

        // System.out.println("¿Tiene el foco? " + this.isFocusOwner());


        //Window.getWindows()[0].toFront();
        //Window.getWindows()[0].repaint();
        //Window.getWindows()[0].setVisible(true);


        System.out.println("Numero de ventanas en MainWindow: " + Window.getWindows().length);
        Window[] windows = Window.getWindows();
        for (Window window : windows) {
            System.out.println(window.getName() + ": " + window.getClass());
        }

        /*int contador = 1;
        for (Window win : Window.getWindows()) {
        //win.toFront();
        if (win instanceof MainWindow) {
        if (win.equals(this)) {
        System.out.println("Es la ventana principal");
        win.setVisible(true);
        win.toFront();
        win.setAlwaysOnTop(true);
        win.setAlwaysOnTop(false);
        win.repaint();
        win.setVisible(false);
        win.setVisible(true);
        win.requestFocus();
        System.out.println(win.requestFocusInWindow());
        System.out.println(win.getFocusableWindowState());
        } else {
        System.out.println("esta ventana no debería existir");
        }
        }
        boolean focusable = win.isFocusableWindow();
        boolean focused = win.isFocused();
        boolean showing = win.isShowing();
        System.out.println("La ventana " + contador + ((focusable) ? "" : "no ") + " es focusable, " + ((focused) ? "" : "no ") + "está focused, " + ((showing) ? "" : "no ") + "está showing");
        contador++;
        }*/

        //Una vez ya hemos recuperado el punto ponemos la variable a false para que los demás SCOs no intenten recuperar el punto
        oCL.restored = false;


    }

    public static void main(String[] args) {

        instance = new MainWindow(false);

        instance.setUndecorated(true);

        //System.out.println((new java.io.File(".").getAbsolutePath()));

        //instance.getClass().getClassLoader().getResourceAsStream("options.properties");
        //ResourceBundle bnd = ResourceBundle.getBundle("tmaestroplayer.config.options");
        //bnd.getString("rutascorm");


        //String FICHERO_CONFIGURACION = System.getProperty("user.dir") + File.separator + "config" + File.separator + "tmaestroplayer" + File.separator + "options.properties";
        //System.out.println("Fichero de configuración " + FICHERO_CONFIGURACION);
        InputStream is = null;


             is = Main.class.getResourceAsStream("/config/options.properties");
            //is = new FileInputStream(new File(FICHERO_CONFIGURACION));
            //prop.load(is);

        
        Properties options = new Properties();

        try {
            options.load(is);
            //Leemos la configuracion del fichero
            //options.load( MainWindow.class.getResourceAsStream("/tmaestroplayer/config/options.properties"));

        } catch (IOException ex) {
            ex.printStackTrace();

        }

       // instance.rutaScorm = options.getProperty("rutascorm");
       // instance.nombreCurso = options.getProperty("nombrecurso");
        instance.fullScreen = options.getProperty("fullscreen");

        //instance.rutaScorm = "file:///D:/Cursos/";
        //instance.nombreCurso = "Cocina/";

        instance.setLayout(null);
        instance.setBounds(0, 0, 800, 600);

        JLabel jLabelBackgroundTop = new JLabel();
        jLabelBackgroundTop.setBackground(Color.BLACK);
        jLabelBackgroundTop.setOpaque(true);
        jLabelBackgroundTop.setBounds(0, 0, 800, 12);

        JLabel jLabelBackgroundBottom = new JLabel();
        jLabelBackgroundBottom.setBackground(Color.BLACK);
        jLabelBackgroundBottom.setOpaque(true);
        jLabelBackgroundBottom.setBounds(0, 588, 800, 12);

        JLabel jLabelBackgroundLeft = new JLabel();
        jLabelBackgroundLeft.setBackground(Color.BLACK);
        jLabelBackgroundLeft.setOpaque(true);
        jLabelBackgroundLeft.setBounds(0, 0, 40, 600);

        JLabel jLabelBackgroundRight = new JLabel();
        jLabelBackgroundRight.setBackground(Color.BLACK);
        jLabelBackgroundRight.setOpaque(true);
        jLabelBackgroundRight.setBounds(760, 0, 40, 600);

        instance.add(jLabelBackgroundTop);
        instance.add(jLabelBackgroundBottom);
        instance.add(jLabelBackgroundLeft);
        instance.add(jLabelBackgroundRight);

        //instance.oGLF = new GraphicalLoginFrame(instance);
        //instance.panel = (JDesktopPane) instance.oGLF.getVisual();

        instance.add(instance.panel);


        //instance.registerKeyboardActions();

        instance.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);



        instance.setVisible(true);



        //Para pantalla completa
        if (instance.fullScreen.equals("true")) {
            GraphicsDevice myDevice = java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();

            if (myDevice.isFullScreenSupported()) {

                System.out.println("Soporta pantalla completa");

                myDevice.setFullScreenWindow(instance);

                myDevice.setDisplayMode(new DisplayMode(800, 600, 32, 60));

            } else {
                System.out.println("No soporta pantalla completa");

            }
        }

        //instance.panel.setSelectedFrame(instance.oGLF);
        //instance.requestFocus();
        //instance.panel.requestFocusInWindow();
        //instance.panel.getDesktopManager().activateFrame(instance.oGLF);

    }

    private void registerKeyboardActions() {
        KeyboardAction upAction = new KeyboardAction(panel, "up");
        KeyboardAction downAction = new KeyboardAction(panel, "down");
        KeyboardAction leftAction = new KeyboardAction(panel, "left");
        KeyboardAction rightAction = new KeyboardAction(panel, "right");
        KeyboardAction enterAction = new KeyboardAction(panel, "enter");

        InputMap panelInputMap = panel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        panelInputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "upAction");
        panelInputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "downAction");
        panelInputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "leftAction");
        panelInputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "rightAction");
        panelInputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enterAction");

        ActionMap panelActionMap = panel.getActionMap();
        panelActionMap.put("upAction", upAction);
        panelActionMap.put("downAction", downAction);
        panelActionMap.put("leftAction", leftAction);
        panelActionMap.put("rightAction", rightAction);
        panelActionMap.put("enterAction", enterAction);

    }

    @Override
    public void controllerUpdate(ControllerEvent oCE) {
        if (oCE instanceof EndOfMediaEvent) {
            //System.out.println("reiniciando el reproductor de música de fondo");
            System.out.println("musicstart");
            bgMusicPlayer.setMediaTime(new Time(0));
            bgMusicPlayer.start();
            /*JInternalFrame jif = applet.panel.getSelectedFrame();
            if (jif instanceof LoginFrame) {
            System.out.println("Está seleccionada la loginFrame");
            } else if (jif instanceof VentanaSeleccionUnidad) {
            String vsuName = ((VentanaSeleccionUnidad) jif).unidadPrincipal.getName();
            System.out.println("Está seleccionada la vsu: " + vsuName);
            } else {
            System.out.println("No se de que tipo es la JInternalFrame");
            }*/




        } else if (oCE instanceof StartEvent) {
            // System.out.println("**player started");
        } else if (oCE instanceof StopEvent) {
            System.out.println("**player stopped!!");

        }
    }

    public CourseLoader getCourseLoader() {
        return oCL;

    }
}
