package de.nplusc.izc.YTutil;


import de.nplusc.izc.tools.IOtools.FileTK;
import de.nplusc.izc.tools.baseTools.Tools;
import java.io.File;
import java.util.prefs.Preferences;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

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

    /**
     * Creates new form UI
     */
    public UI()
    {
        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()
    {

        txfYTURl = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        btnDL = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        logPane = new javax.swing.JTextArea();
        btnAltDl = new javax.swing.JButton();
        Cancel = new javax.swing.JButton();
        killPath = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Video-URL hier einfügen");

        btnDL.setText("Laden");
        btnDL.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                btnDLActionPerformed(evt);
            }
        });

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

        btnAltDl.setText("alternatives Verzeichnis verwenden");

        Cancel.setText("Abbrechen");
        Cancel.setEnabled(false);
        Cancel.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                CancelActionPerformed(evt);
            }
        });

        killPath.setText("Pfad zurücksetzen");
        killPath.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                killPathActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(101, 101, 101)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(btnDL, javax.swing.GroupLayout.PREFERRED_SIZE, 531, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txfYTURl, javax.swing.GroupLayout.PREFERRED_SIZE, 531, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 104, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addComponent(killPath)
                .addGap(33, 33, 33)
                .addComponent(btnAltDl, javax.swing.GroupLayout.PREFERRED_SIZE, 395, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(Cancel)
                .addGap(41, 41, 41))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txfYTURl, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btnDL, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(37, 37, 37)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAltDl, javax.swing.GroupLayout.DEFAULT_SIZE, 60, Short.MAX_VALUE)
                    .addComponent(Cancel)
                    .addComponent(killPath))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18))
        );

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

    private void btnDLActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnDLActionPerformed
    {//GEN-HEADEREND:event_btnDLActionPerformed
        
        /*if(Preferences.userRoot().get("izyt.path", "...").equals("..."))
        {
            if(!FileTK.checkDirExist(Preferences.userRoot().get("izyt.path", "...")))//falls Pfad irgendwie ungültig wurde
            {
            String targetDirectory = Tools.FileChooseDlg(this, true, true, new String[]{});
            Preferences.userRoot().put("izyt.path", targetDirectory);
            }
        }*/
        if(Preferences.userRoot().get("izyt.path", "...").equals("...")||(!FileTK.checkDirExist(Preferences.userRoot().get("izyt.path", "..."))))//falls Pfad irgendwie ungültig wurde
        {
            String targetDirectory = Tools.FileChooseDlg(this, true, true, new String[]{});
            Preferences.userRoot().put("izyt.path", targetDirectory);
        }
        String tdir = Preferences.userRoot().get("izyt.path", "...");
        System.out.println(tdir);
        download(txfYTURl.getText(),tdir);
    }//GEN-LAST:event_btnDLActionPerformed

    private void killPathActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_killPathActionPerformed
    {//GEN-HEADEREND:event_killPathActionPerformed
        Preferences.userRoot().put("izyt.path", "...");
    }//GEN-LAST:event_killPathActionPerformed

    private void CancelActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_CancelActionPerformed
    {//GEN-HEADEREND:event_CancelActionPerformed
        isCancelled=true;
        Tools.runSingleCmd(true, true, false, true, logPane,
            System.out,"taskkill", "/f" , "/im","youtube-dl.exe");
        Tools.runSingleCmd(true, true, false, true, logPane,
            System.out,"taskkill", "/f" , "/im","ffmpeg.exe");
        toggleDownloadAndCancelButton(true);
    }//GEN-LAST:event_CancelActionPerformed

    
    
    private void toggleDownloadAndCancelButton(boolean loadReady)
    {
        btnDL.setEnabled(loadReady);
        btnAltDl.setEnabled(loadReady);
        Cancel.setEnabled(!loadReady);
    }
    
    private boolean isCancelled=false;
    
    public void download(final String yturl, final String path)
    {
        toggleDownloadAndCancelButton(false);
        isCancelled=false;
        new Thread(new Runnable()
        {
            public void run()//http://www.youtube.com/watch?v=oHg5SJYRHA0
            {
                String tempPath = Tools.processEnvVarsinLine("%temp%\\iZYT");
                FileTK.ensuredirExistence(tempPath);
                Tools.runCmdWithOutToTextField(logPane,"youtube-dl.exe", "-o", tempPath + "\\%(title)s.flv", "--restrict-filenames", "--newline", yturl);
                String loadedFile = FileTK.getDirectoryContent(tempPath, true)[0];
                System.out.println(loadedFile);
                String inPath = tempPath+"\\"+loadedFile;
                String outpath = path+"\\"+FileTK.getFileName(loadedFile)+"";//.mp3
                System.out.println(outpath);
                if(!isCancelled)
                {
                    // FileTK.kopierpaste(new File(inPath), new File(outpath));
                    Tools.runCmdWithOutToTextField(logPane,"ffmpeg.exe","-stats","-n","-i",inPath,"-ab","192k",outpath);
                }
                //ffmpeg --stats -b 192k -i inputfile out.mp3
                FileTK.verzeichnisKillen(new File(tempPath));
                toggleDownloadAndCancelButton(true);
            }
        }).start();
    }
    
    
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[])
    {
        /* 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(UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (InstantiationException ex)
        {
            java.util.logging.Logger.getLogger(UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (IllegalAccessException ex)
        {
            java.util.logging.Logger.getLogger(UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (javax.swing.UnsupportedLookAndFeelException ex)
        {
            java.util.logging.Logger.getLogger(UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        boolean unpackResources=false;
        
        //TODO resourcehandling
        
        //initRsrcs()
        String resrcsver = Preferences.userRoot().get("izyt.exttools", "...");
        
        if(resrcsver.equals("..."))
        {
            unpackResources=true;
        }
        else
        {
            int resver = Integer.valueOf(resrcsver);
            if(resver<001)
            {
                unpackResources=true;
            }
        }
        
        if(unpackResources)
        {
            new File("ffmpeg.exe").delete();
            new File("youtube-dl.exe").delete();
            Tools.runSingleCmd(true,true,false,true,null, System.out, "java","-jar","YTUtil-programs.jar");
            new File("zzz_sfxmod.jar").delete();//sfxmodul killen
            if(!Preferences.userRoot().getBoolean("Toolkit.enableCoreDebug", false))
            {
                new File("YTUtil-programs.jar").delete();//resource-bundle löschen; für debugging deaktiviert
                Preferences.userRoot().put("izyt.exttools", "001");//deaktiviert das Rsrcbundle bis zu neurer version
            }
        }
        
        Tools.runSingleCmd(true,true,false,true,null, System.out, "youtube-dl.exe","-U");//checken nach Updates
        
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                new UI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Cancel;
    private javax.swing.JButton btnAltDl;
    private javax.swing.JButton btnDL;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton killPath;
    private javax.swing.JTextArea logPane;
    private javax.swing.JTextField txfYTURl;
    // End of variables declaration//GEN-END:variables
}
