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

import com.coremedia.iso.IsoFile;
import de.nplusc.izc.tools.IOtools.FileTK;
import de.nplusc.izc.tools.baseTools.Messagers;
import de.nplusc.izc.tools.baseTools.Tools;
import de.nplusc.izc.tools.baseTools.arraytools;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.channels.ReadableByteChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.prefs.Preferences;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.JTextArea;

/**
 *
 * @author LH
 */
public class BurnMe
{
    
    private static String burnprogP;
    private static String ffmpegpath;
    private static String devideID;
    public static void Configure()
    {
        
        
        
        String cdrpath = Preferences.userRoot().get("izpl.cdrpath", "...");
        if(cdrpath.equals("..."))
        {
            Messagers.SingleLineMsg("Navigate to CDRutils", "Okay");
            Preferences.userRoot().put("izpl.cdrpath", Tools.FileChooseDlg(new JFrame(), true, false, new String[]
            {
                "exe"
            }));
        }
        cdrpath = FileTK.getFilePath(Preferences.userRoot().get("izpl.cdrpath", "..."));
        burnprogP=cdrpath;
        
        String ffmp = Preferences.userRoot().get("izpl.ffm", "...");
        if(ffmp.equals("..."))
        {
            Messagers.SingleLineMsg("Navigate to ffmpeg", "Okay");
            Preferences.userRoot().put("izpl.ffm", Tools.FileChooseDlg(new JFrame(), true, false, new String[]
            {
                "exe"
            }));
        }
        ffmp = FileTK.getFilePath(Preferences.userRoot().get("izpl.ffm", "..."));
        ffmpegpath = ffmp;
        
        String drv = Preferences.userRoot().get("izpl.defaultBurner", "...");
        if(drv.equals("..."))
        {
            JTextArea t = new JTextArea();
            Tools.runSingleCmd(true, true, true,true,t, cdrpath+"\\cdrecord", "-scanbus");
            System.out.println(t.getText());
            String[] scsitemp = t.getText().split("\\n");
            ArrayList<String> validEntries = new ArrayList<>();
            for (int i = 0; i < scsitemp.length; i++)
            {
                String l = scsitemp[i];
                if(l.startsWith("scsibus")||l.startsWith("Cdrecord")||l.startsWith("Using")||l.endsWith("Disk")||l.endsWith("HOST ADAPTOR")||l.endsWith("*"))
                    scsitemp[i]=null;//nondevice-lines
                else
                {
                    validEntries.add(l);
                }
            }
            String[] s = validEntries.toArray(new String[]{});
            drv = Tools.listSelectorPopup(s, "Brenner auswählen").trim().substring(0,5);
            Preferences.userRoot().put("izpl.defaultBurner", drv);
        }
        devideID=drv;
    }
    
    
    
    public static void InitializeBurnDisc(String srcpath)
    {
        Configure();
        List<String[]> data = PLReader.readList(srcpath, true);
        List<String[]> rawList = new ArrayList<>();//2. element gint GruppenID an//3. die TrackLänge //in tabelle spalte 4 = disk#
        int tGID = 0;
        for (String[] Grps : data)
        {
            for (String element : Grps)
            {
                AudioInputStream in = null;
                try
                {
                    String path = element.split("\\n")[1];
                    //if(path)
                    String ext = FileTK.getFileExt(path).toLowerCase();
                    int lengthInSec = 0;
                    String[] dataset = new String[3];
                    dataset[0] = path;
                    File audio = new File(path);
                    System.err.println(path);
                    switch (ext)
                    {
                        case "mp3"://falltrhu intended
                        case "ogg":
                        //case "m4a":
                            AudioFileFormat baseFileFormat = AudioSystem.getAudioFileFormat(audio);
                            Map properties = baseFileFormat.properties();
                            Long duration = (Long) properties.get("duration")/1000000;
                            lengthInSec = (int)(duration+0);//????
                        break;
                        case "wav":
                            in = AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED, AudioSystem.getAudioInputStream(audio));
                            lengthInSec = (int) (in.getFrameLength()/(long)in.getFormat().getFrameRate()); // berechnung für wav
                        break;
                            
                        case "m4a":
                        case "mp4":
                        case "aac":
                            IsoFile isoFile = new IsoFile(new FileInputStream(path).getChannel());
                            double lengthInSeconds = (double)
                            isoFile.getMovieBox().getMovieHeaderBox().getDuration() /
                            isoFile.getMovieBox().getMovieHeaderBox().getTimescale();
                            lengthInSec = (int) (lengthInSeconds+0);
                        break;    
                        default:
                            
                        break;
                        
                    }
                    dataset[1] = tGID+"";
                    dataset[2] = lengthInSec+"";
                    if(!(lengthInSec==0))
                        rawList.add(dataset);
                    System.out.println(lengthInSec);
                }
                catch (UnsupportedAudioFileException | IOException ex)
                {
                    ex.printStackTrace();
                }
                finally
                {
                    try
                    {
                        if(in !=null)
                            in.close();
                    }
                    catch (IOException ex)
                    {
                        ex.printStackTrace();
                    }
                }
            }
            tGID++;
        }
        if(rawList.size()==0)
            return; //nicht weitermachen bei leerer liste
        //handing over to stage 2 aka the Ordering
        new BurnLiistManager(rawList).setVisible(true);   
    }
    private static BurnProgressGUI bpg;
    private static List<List<String[]>> disks;
    public static void burnDisk(List<String[]> tracks)
    {
        
        List<String[]> disk= new ArrayList<>();
        disks = new ArrayList<>();
        int secondsFromStart=0;
        int DiskMax = 70*60;
        for (String[] dataset : tracks)
        {
            int secs = Integer.valueOf(dataset[2]);
            secondsFromStart+=secs;
            if(secondsFromStart>DiskMax)
            {
                disks.add(disk);
                disk = new ArrayList<>();
                secondsFromStart=secs;
            }
        disk.add(dataset);
        }
        disks.add(disk);
        
        bpg = new BurnProgressGUI();
        bpg.setVisible(true);
        
        new Thread(
            new Runnable()
            {

                @Override
                public void run()
                {
                    //manage Burrn itself
                    int disksToDo = disks.size();
                    int done =0;
                    JProgressBar status = bpg.getDiskProgress();
                    status.setMaximum(disksToDo);
                    JTextArea logg = bpg.getLogPane();
                    for (List<String[]> list : disks)
                    {
                        //Tools.runSingleCmd(true, true, true, true, logg, new String[]{"ping","google.de"});
                        FileTK.ensuredirExistence(Tools.processEnvVarsinLine("%temp%\\izpl\\burncache\\cache.map"));
                        String[] filesForCmd = new String[list.size()];
                        for (int i = 0; i < list.size(); i++)
                        {
                            String[] set = list.get(i);
                            String fn = FileTK.getFileName(set[0]);
                            filesForCmd[i] = Tools.processEnvVarsinLine("%temp%\\izpl\\burncache")+"\\"+fn+".wav";
                            //ffmpeg -i input.xxx -acodec pcm_s16le -ac 2 -f wav output.wav
                            Tools.runSingleCmd(true, true, true, true, logg, new String[]{ffmpegpath+"\\ffmpeg","-i",set[0],"-acodec","pcm_s16le","-ar","44100","-ac", "2",/* "-f", "wav ",*/ filesForCmd[i]});
                        }
                        done++;
                        status.setValue(done);
                        //Toasten cdrecord -v dev=ATAPI:0,0,0 -audio -pad *.wav
                        String[] temp = arraytools.concatAll( new String[]{burnprogP+"\\cdrecord","-v","dev="+devideID,"-audio","-pad"},filesForCmd);
                        
                        //System.out.println(arraytools.ArrayKleben(temp, " "));
                        String t2 = "";
                        for (String string : temp)
                        {
                            t2+=" "+string;
                        }
                        
                        System.out.println(t2);
                        //Tools.runSingleCmd(true, true, true, true, logg,temp);
                        //FileTK.verzeichnisKillen(new File(Tools.processEnvVarsinLine("%temp%\\izpl\\burncache\\")));
                    }
                    
                    
                    
                    //Builder.quickQuit();
                }
            }
        ).start();
        
        //ffmpeg -i input.xxx -acodec pcm_s16le -ac 2 -f wav output.wav
        
    }
}
