/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.nplusc.izc.iZpl;

import de.nplusc.izc.tools.IOtools.FileTK;
import de.nplusc.izc.tools.IOtools.LogStream;
import de.nplusc.izc.tools.baseTools.Messagers;
import de.nplusc.izc.tools.baseTools.Tools;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Date;
import java.util.prefs.Preferences;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import org.yaml.snakeyaml.Yaml;

/**
 *
 * @author LH
 */
public class Builder extends javax.swing.JFrame
{

    /**
     * Creates new form Builder
     */
    public Builder()
    {
        initComponents();
    }

    /**
     * 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents()
    {

        pload = new javax.swing.JProgressBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Loading.......");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pload, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pload, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    /**
     * @param args the command line arguments
     */
    private static boolean loadedVLC = false;
    private static PLServer ps = null;
    private static Boolean forcePregen = false;
    public static boolean issueDetected = false;
    
    
    
    
    public static void main(final String args[])
    {
        /* psOut = new PrintStream(
         new BufferedOutputStream(new FileOutputStream(
         new File("iZpl.log"))), true);
         psOut2 = new PrintStream(
         new BufferedOutputStream(new FileOutputStream(
         new File("iZpl-e.log"))), true);*/
        /*System.setOut(psOut);
         System.setErr(psOut2);
         String time = new Date(System.currentTimeMillis()).toString();
         System.out.println("IZPL-Core:initialized at:"+time);*/

//TODO: liveEdit (wird mit ner speziellen URL aktiviert
//TODO:  GUI-Editor zum Erzeugen von iZpl-S
            /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try
        {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
            {
                if ("Nimbus".equals(info.getName()))
                {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        }
        catch (ClassNotFoundException ex)
        {
            java.util.logging.Logger.getLogger(Builder.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (InstantiationException ex)
        {
            java.util.logging.Logger.getLogger(Builder.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (IllegalAccessException ex)
        {
            java.util.logging.Logger.getLogger(Builder.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (javax.swing.UnsupportedLookAndFeelException ex)
        {
            java.util.logging.Logger.getLogger(Builder.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
            /* Create and display the form */

        java.awt.EventQueue.invokeLater(new Runnable()
        {
            @SuppressWarnings("ResultOfObjectAllocationIgnored")
            @Override
            public void run()
            {
                if (args.length > 0 && (args[0].equals("--file") || args[0].equals("--state")))
                {
                    if (args.length == 1)
                    {
                        System.out.println("Uhhh Scheissdreck eingegeben....");
                        try
                        {
                            Thread.sleep(3000);
                        }
                        catch (InterruptedException ex)
                        {
                            ex.printStackTrace();
                        }
                        return;
                    }
                    final Builder b = new Builder();
                    pload.setIndeterminate(true);
                    b.setVisible(true);

                    new Thread(new Runnable()
                    {
                        @SuppressWarnings("ResultOfObjectAllocationIgnored")
                        @Override
                        public void run()
                        {
                            String time ="";
                            Yaml y = new Yaml();
                            String vlcpath = "...";
                            try
                            {
                                if (Boolean.valueOf(Preferences.userRoot().get("izpl.enableFastDebug", "false")))
                                {
                                    System.out.println("lfe");
                                    PrintStream psOut = new LogStream(
                                            new BufferedOutputStream(new FileOutputStream(
                                            new File("iZpl.log"))), true);
                                    System.setOut(psOut);
                                    PrintStream psOut2 = new LogStream(
                                            new BufferedOutputStream(new FileOutputStream(
                                            new File("iZpl-e.log"))), true);
                                    System.setErr(psOut2);
                                }
                            }
                            catch (Exception e)//danke du komisher javabug
                            {
                            }
                            try
                            {
                                time = new Date(System.currentTimeMillis()).toString();
                                System.out.println("IZPL-Core:initialized at:" + time);
                                vlcpath = Preferences.userRoot().get("izpl.vlcpath", "...");
                            }
                            catch (Exception e)//danke du komisher javabug
                            {
                               System.out.println(e.getMessage());
                               System.out.println(e.toString());
                               e.printStackTrace();
                               
                            }
                            //String vlcpath="...";
                            if (vlcpath.equals("..."))
                            {
                                Preferences.userRoot().put("izpl.vlcpath", Tools.FileChooseDlg(new JFrame(), true, false, new String[]
                                {
                                    "exe"
                                }));
                                vlcpath = Preferences.userRoot().get("izpl.vlcpath", "...");
                            }
                            System.err.println(vlcpath);
                            boolean isShittyPlayer = false;
                            boolean isWMShit = false;
                            boolean isOtherShit = false;
                            if (FileTK.getFileName(vlcpath).equalsIgnoreCase("wmplayer.exe")
                                    || FileTK.getFileName(vlcpath).equalsIgnoreCase("winamp.exe")
                                    || FileTK.getFileName(vlcpath).equalsIgnoreCase("foobar2000"))
                            {
                                isShittyPlayer = true;
                            }
                            
                            try
                            {
                                if (args.length > 2 && args[2].equals("--pregen"))
                                {
                                    forcePregen = true;
                                }
                                
                                System.out.println("fpl|"+forcePregen+"|shitmp|"+isShittyPlayer+"|a1|"+args[1]+"|vp|"+vlcpath);
                                if (args[0].equals("--file")&&!(forcePregen||isShittyPlayer))
                                {
                                    ps = new PLServer(/*"D:\\mp3\\iZpl\\rxe.izpl"/*/args[1]/**/);//DBG_CD3
                                    if(issueDetected)
                                    {
                                        quickQuit();
                                    }
                                }
                                else//RELOADER
                                {
                                    if(!(forcePregen||isShittyPlayer))
                                    {
                                        FileReader plf = new FileReader(args[1]);
                                        PlProcessor pp = (PlProcessor) y.load(plf);
                                        plf.close();
                                        ps = new PLServer(pp);
                                    }
                                    System.err.println("TheFUQ");
                                }
                                //http://localhost:9263/lst.m3u
                                if (isShittyPlayer|| forcePregen)
                                {
                                    PlProcessor ppp = new PlProcessor();
                                    ppp.InitializeOnPath(args[1]);
                                    if(issueDetected)
                                    {
                                        quickQuit();
                                    }
                                    // <editor-fold defaultstate="collapsed" desc="Altlast">     
                                        /*if(!Boolean.valueOf(Preferences.userRoot().get("izpl.AlertShown", "false")))
                                     {
                                     if(FileTK.getFileName(vlcpath).equalsIgnoreCase("wmplayer.exe"))
                                     {
                                     Messagers.SingleLineMsg("WMP unterstützt nicht alle Funktionen", "Okay....");
                                     }
                                     else
                                     {
                                     if(FileTK.getFileName(vlcpath).equalsIgnoreCase("winamp.exe"))
                                     {
                                     Messagers.SingleLineMsg("Winamp mag mich nicht", "Okay....");
                                     }
                                                    
                                     else
                                     {
                                     if(FileTK.getFileName(vlcpath).equalsIgnoreCase("foobar2000.exe"))
                                     {
                                     Messagers.SingleLineMsg("Fb2K kann leider nicht Nachladen", "Okay....");
                                     }
                                     }
                                     }
                                     Messagers.SingleLineMsg("VLC MEdia-Player wird empfohlen", "Okay....");
                                     Preferences.userRoot().put("izpl.AlertShown", "true");
                                     }*/
                                    //</editor-fold>
                                    if (FileTK.getFileName(vlcpath).equalsIgnoreCase("wmplayer.exe"))
                                    {
                                        isWMShit = true;
                                    }
                                    else
                                    {
                                        isOtherShit = true;
                                    }
                                    //dank an M$ dass irh unbedingt preloaden müsst. muss vorgenerieren und die lsite terminieren damits keine endlosloadschleife gibt...
                                    int elemsforPreload = ppp.getPoolSize() * 3;
                                    while (elemsforPreload < 200)//falls liste sehr kurz ist.
                                    {
                                        elemsforPreload *= 3;
                                    }
                                    System.err.println("elemstogen|"+elemsforPreload);
                                    String wmplist = "";
                                    for (int i = 0; i < elemsforPreload; i++)
                                    {
                                        wmplist = wmplist + "\n" + ppp.getBlock();
                                    }
                                    //ps.ppp.setFailRSP(wmplist);
                                    System.err.println("Loop'd");
                                    FileTK.writeFile("#extm3u+n" + wmplist, "wmpload.m3u");
                                }

                                if (!isWMShit && !isOtherShit)
                                {
                                    loadedVLC = true;
                                    do
                                    {
                                        Tools.runSingleCmd(false, true, false, true, new JTextArea(), vlcpath,/*"--extraintf=http:logger","--verbose=2","--file-logging","--logfile=vlc-log.txt",*/ "http://localhost:9263/rcvr/lst.m3u");//http://localhost:9263/lst.m3u");
                                    }
                                    while (Tools.execCrashed);
                                }
                                else
                                {
                                    if (isWMShit)
                                    {
                                        Tools.runSingleCmd(false, true, false, true, new JTextArea(), vlcpath, "/prefetch:6", "/Open", new File("wmpload.m3u").getAbsolutePath());
                                    }
                                    else
                                    {
                                        if (!forcePregen)
                                        {
                                            Tools.runSingleCmd(false, true, false, true, new JTextArea(), vlcpath, new File("wmpload.m3u").getAbsolutePath());
                                        }

                                    }
                                }
                                System.err.println("<<<");
                                time = new Date(System.currentTimeMillis()).toString();
                                System.out.println("IZPL-Core:Checkpoint erstellen:" + time);
                                //muss nen StateSaver hier reintoasten....
                                if(!(forcePregen||isShittyPlayer))
                                {
                                    String pp = y.dump(ps.ppp);
                                    FileTK.writeFile(pp, "state.iZcont");
                                }
                                quickQuit();
                            }
                            catch (FileNotFoundException ex)
                            {
                                ex.printStackTrace();
                            }
                            catch (IOException ex)
                            {
                                ex.printStackTrace();
                            }
                            finally
                            {
                                //psOut.close();
                            }
                        }
                    }).start();
                    new Thread(new Runnable()
                    {
                        @SuppressWarnings("ResultOfObjectAllocationIgnored")
                        @Override
                        public void run()
                        {

                            try
                            {
                                while (!loadedVLC)
                                {
                                    Thread.sleep(150);
                                }
                                Thread.sleep(1500);
                            }
                            catch (InterruptedException ex)
                            {
                                ex.printStackTrace();
                            }
                            b.setVisible(false);
                        }
                    }).start();
                    //kommt erst bei VLCexit......
                    //halt
                    //ArrayList<String[]> catcher = PLReader.readList("D:\\mp3\\iZpl\\root.izpl");
                    //.err.println("NOP");
                    //new Builder().setVisible(true);
                }
                else
                {
                    //BuilderGUI
                }
            }
        });
    }
    
    private static void quickQuit()
    {
        String time2 = new Date(System.currentTimeMillis()).toString();
        System.err.println("IZPL-Core:SHitdown at:" + time2);
        System.out.println("IZPL-Core:SHitdown at:" + time2);
        System.exit(0);
    }
    
    
    /*
     * Changelog:
     * V0.1.0: First build; basic functionality for reading in the format; No Failsafe system. Relaod resetted the stte
     * V0.1.1: added a failsafe system incase VLC crashes or hangs;
     * V0.1.1b: squashed a bug caused by J7U17 on Runtime.exec();
     * V0.1.2: made a pausing system for exiting the program regulary
     * V0.1.3 made reload better (fixed the complete reset of the sstate)
     * V0.1.3b: Fixed a bug that trolled me since V1.0 (that the raw list got added as a playall block, too. was due to a forgotten list.remove(0)
     * V0.1.4 added compatibility layer for WMP adn winamp (They hate the dynamic loading from a localhosted server)
     * V0.1.5.1 added a Force-Pregen to List and some preparations to work serverless on Pregeneration
     * V0.1.5.2 finalised de-serverisation //preparation for upcoming changes//BAD BUILD
     * V0.1.5.3 Fixed some bugs and added a failguard incase of file not existing
     * NOTE: converted to SVN
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private static javax.swing.JProgressBar pload;
    // End of variables declaration//GEN-END:variables
}
