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

import de.nplusc.izc.tools.IOtools.FileTK;
import de.nplusc.izc.tools.UiToolz.BootStrap;
import de.nplusc.izc.tools.baseTools.Lock;
import de.nplusc.izc.tools.baseTools.Messagers;
import de.nplusc.izc.tools.baseTools.Tools;
import de.nplusc.izc.tools.baseTools.arraytools;
import java.awt.Point;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import javax.swing.UIManager;
        

/**
 *
 * @author LH
 */
public class InstallProgressGui extends javax.swing.JFrame
{
    InstallManager im = InstallManager.Main;
    private boolean autoExit = true;
    private boolean packMode = false;//ändert GUI ein hisschen und arbeitet ne zweite queue ab
    private String[] packList;
    private Lock l = new Lock();
    /**
     * Creates new form InstallProgressGui
     */
    public InstallProgressGui()
    {

        initComponents();
        updatePosition();
        btnExit.setVisible(false);
        pbarPacks.setVisible(false);
        startInstallation();
        
    }
    private void updatePosition()
    {
        lblVID.setText(InstallManager.VERSION_GUI_TXT);
        Point p = new Point(ModeSel.topleft_coords_x, ModeSel.topleft_coords_y);
        setLocation(p);
    }
    public InstallProgressGui(String[] packQueue)
    {
        Tools.DebugHelperPrint("PAck", true, "iZsetup.enableCoreDebug");
        initComponents();
        updatePosition();
        pbarPacks.setVisible(true);
        btnExit.setVisible(false);
        packList = packQueue;
        startPackInstall();
    }
    public void startPackInstall()
    {
        ArrayList<String> packListCopyTemp = new ArrayList<>();
        for (String qe : packList)
        {
            String comparer = qe.substring(0,9);
            if(comparer.equalsIgnoreCase("packfile:"))
                packListCopyTemp.add(qe);
        }
        pbarPacks.setMaximum(packListCopyTemp.size());
        pbarPacks.setMinimum(0);
        pbarPacks.setValue(0);
        packMode=true;
        autoExit=false;
        new Thread(new Runnable()
        {
            @Override
            @SuppressWarnings("SleepWhileInLoop")
            public void run()
            {
                try
                {
                    BootStrap.bootLock.lock();
                    BootStrap.bootLock.unlock();
                }
                catch (InterruptedException ex)
                {
                    ex.printStackTrace();
                }
                for (String packcmd : packList)
                {
                    im =new InstallManager();
                    String fileToHandle = packcmd.substring(9);
                    //substring(9)
                    String comparer = packcmd.substring(0,9);
                    String metadata = packcmd.substring(9);
                    if(comparer.equalsIgnoreCase("packfile:"))
                    {
                        im.setInstallScript(fileToHandle);
                        im.createQueue();
                        try
                        {
                            Tools.DebugHelperPrint("", true, "iZsetup.enableCoreDebug");
                            l.lock();//das 2. geht erst durch wenn von wo anderst geunlockt wurde;
                            startInstallation();
                            
                            l.lock();
                            Tools.DebugHelperPrint("UnloxDetected", true, "iZsetup.enableCoreDebug");
                            l.unlock();    
                        }
                        catch (InterruptedException ex)
                        {
                            ex.printStackTrace();
                        }
                        pbarPacks.setValue(pbarPacks.getValue()+1);
                    }
                    if(comparer.equalsIgnoreCase("waitdisk:"))
                    {
                        Tools.DebugHelperPrint("WaitDetected;", true, "iZsetup.enableCoreDebug");
                        boolean rightDisk = FileTK.checkDirExist(fileToHandle);
                        while(!rightDisk)
                        {
                            Messagers.SingleLineMsg("Erwarte DIsk:"+metadata, "OKee...");
                            rightDisk = FileTK.checkDirExist(fileToHandle);
                        }
                        
                    }
                    
                }
                btnExit.setVisible(true);
                
            }
        }).start();
    }
    
    public void startInstallation()
    {

        int count = im.getInstallQueue().length;
        ptotal.setMinimum(0);
        ptotal.setValue(0);
        ptotal.setMaximum((count/2));
        if(packMode)
            ptotal.setMaximum((count/2)-1);
        
        new Thread(new Runnable()
        {

            @Override
            @SuppressWarnings("SleepWhileInLoop")
            public void run()
            {
                try
                {
                    BootStrap.bootLock.lock();
                    BootStrap.bootLock.unlock();
                }
                catch (InterruptedException ex)
                {
                    ex.printStackTrace();
                }
                String[][] queue = im.getInstallQueue();
                for (int i = 0; i + 1 < queue.length; i++)
                {
                    String msg = queue[i][0];
                    tempLog.append(lblMsg.getText() + "\n");//Trockentest für Cmd-s
                    lblMsg.setText(msg);
                    i++;
                    String[] cmd = queue[i];
                    if(!cmd[0].equalsIgnoreCase("wait"))
                    {
                                    //safeguard gegen nullpointer bei <4 strings
                        if((cmd[0].length()>4&&(!cmd[0].substring(0,5).equalsIgnoreCase("Copy:")))||(cmd[0].length()<5))
                        {
                        Tools.DebugHelperPrint(msg, true, "iZsetup.enableFinerDebug");
                        Tools.DebugHelperPrint(cmd[0]/*sollte zumindest grundlegendes über befehl verraten*/, true, "iZsetup.enableFinerDebug");
                        Tools.runSingleCmd(true,true,false,true,tempLog,cmd);//scharfgesetzt
                                            
                        }
                        else
                        {
                            cmd[0] = cmd[0].substring(5);
                            String[] cmdspl = cmd[0].split(">");
                            //File src = new File(cmdspl[0]);
                            File trg = new File(FileTK.getFilePath(cmdspl[1]));
                            trg.mkdirs();
                            try
                            {
                                Files.copy(Paths.get(cmdspl[0]), Paths.get(cmdspl[1]), StandardCopyOption.REPLACE_EXISTING);
                                //copy:src>trg
                            }
                            catch (IOException ex)
                            {
                                ex.printStackTrace();
                            }
                        }
                    }
                    else
                    {
                        autoExit = false;
                    }
                    try
                    {
                        Thread.sleep(1000);
                    }
                    catch (InterruptedException ex)
                    {
                        //ex.printStackTrace();
                    }
                    ptotal.setValue(ptotal.getValue()+1);
                }
                Tools.DebugHelperPrint("...", true, "iZsetup.enableCoreDebug");
                //lblMsg.setText("finito");
                if(!packMode)
                    btnExit.setVisible(true);
                if(autoExit)
                {
                    try
                    {
                        Thread.sleep(20000);
                    }
                    catch (InterruptedException ex)
                    {
                        ex.printStackTrace();
                    }
                }
                else
                {
                    if(!packMode)
                    {
                        System.exit(0);
                    }
                    else
                    {
                        Tools.DebugHelperPrint("unlox", true, "iZsetup.enableCoreDebug");
                        l.unlock();
                    }
                }
            }
        }).start();

    }

    /**
     * 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()
    {

        jScrollPane1 = new javax.swing.JScrollPane();
        tempLog = new javax.swing.JTextArea();
        lblMsg = new javax.swing.JLabel();
        ptotal = new javax.swing.JProgressBar();
        btnExit = new javax.swing.JButton();
        lblVID = new javax.swing.JLabel();
        pbarPacks = new javax.swing.JProgressBar();
        jSeparator3 = new javax.swing.JSeparator();
        jSeparator4 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(852, 331));
        setResizable(false);
        addComponentListener(new java.awt.event.ComponentAdapter()
        {
            public void componentMoved(java.awt.event.ComponentEvent evt)
            {
                formComponentMoved(evt);
            }
        });

        tempLog.setColumns(20);
        tempLog.setRows(5);
        jScrollPane1.setViewportView(tempLog);

        lblMsg.setText("Starte Installixierung");

        btnExit.setText("Beenden");
        btnExit.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                btnExitActionPerformed(evt);
            }
        });

        lblVID.setText("izSetup 1.0.0 (c) 2012 iZc");

        pbarPacks.setMinimum(10);
        pbarPacks.setOrientation(1);
        pbarPacks.setValue(3);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblVID)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jSeparator4))
                    .addComponent(ptotal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(lblMsg, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnExit, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 787, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(pbarPacks, javax.swing.GroupLayout.DEFAULT_SIZE, 39, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(ptotal, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblMsg)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 22, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnExit))
                    .addComponent(pbarPacks, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblVID)
                    .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnExitActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnExitActionPerformed
    {//GEN-HEADEREND:event_btnExitActionPerformed
        System.exit(0);
    }//GEN-LAST:event_btnExitActionPerformed

    private void formComponentMoved(java.awt.event.ComponentEvent evt)//GEN-FIRST:event_formComponentMoved
    {//GEN-HEADEREND:event_formComponentMoved
        ModeSel.topleft_coords_x = getLocation().x;
        ModeSel.topleft_coords_y = getLocation().x;
    }//GEN-LAST:event_formComponentMoved

    /**
     * @param args the command line arguments
     */
    public static void main(String args[])
    {
                        try {
	    UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
	} catch( Exception e ) { 
	    //e.printStackTrace();
	}
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                new InstallProgressGui().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnExit;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JSeparator jSeparator4;
    private javax.swing.JLabel lblMsg;
    private javax.swing.JLabel lblVID;
    private javax.swing.JProgressBar pbarPacks;
    private javax.swing.JProgressBar ptotal;
    private javax.swing.JTextArea tempLog;
    // End of variables declaration//GEN-END:variables
}
