/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package de.nplusc.izc.Utilities.WPCMgr;

import de.nplusc.izc.tools.IOtools.FileTK;
import de.nplusc.izc.tools.baseTools.Tools;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;

/**
 *
 * @author LH
 */
public class Synchronizer
{
    public static void main(String[] args)
    {
        String path = "";
        String res = "";
        if(args.length>1)
        {
        path = args[0];
        res = args[1];
        }
        //DEBUG
        path="T:\\wpc";
        res="1920x1080";
        
        try
        {
            LinkedHashMap<String,Object> data = (LinkedHashMap<String,Object>) new Yaml().load(new FileInputStream(path+"\\00_meta\\state.yml"));
            if(data.get("HEAD")==null)
            {
            initPipeLine(path, res);
            }
            else
            {
                updatePipeLine(path, res);
            }
        }
        catch (FileNotFoundException ex)
        {
            ex.printStackTrace();
        }
        
    }
    
    public static void initPipeLine(String path,String res)
    {
        String[] dirsExist = FileTK.getDirectoryContent(/*args[0]*/path,true);
        final int pid[] = new int[]{0};
        List<String[]> cmdQueue = new ArrayList<>();
        List<String> resultFiles = new ArrayList<>();
        List<String> packagesInitialized = new ArrayList<>();
        Arrays.stream(dirsExist).filter(t -> !t.startsWith("00_") && new File(path+"\\" + t).isDirectory()).forEach(t ->
        {
            packagesInitialized.add(t);
            Object[] rv = processPackage(/*args[0]+*/path+"\\" + t, pid[0]++, res);
            cmdQueue.addAll((List<String[]>) rv[0]);
            resultFiles.addAll((List<String>) rv[1]);
        });
        DumperOptions yamlOptions = new DumperOptions();
        yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
        Yaml y = new Yaml(yamlOptions);

        //FileTK.writeFile(new Yaml().dump(cmdQueue),"T:\\wpc\\00_meta\\debug_.yaml");

            cmdQueue.forEach(x -> Tools.runCmdWithPassthru(System.out, x));
        
        
        try
        {
            LinkedHashMap<String,Object> data = (LinkedHashMap<String,Object>) y.load(new FileInputStream(path+"\\00_meta\\state.yml"));
            String targetDir = (String) data.get("Outdir");
            resultFiles.forEach(entry -> 
            {
                String fn = FileTK.getFileName(entry);
                FileTK.kopierpaste(new File(entry),new File(targetDir+"\\"+fn));
            });
            data.put("HEAD", packagesInitialized);
            String o = y.dump(data);
            FileTK.writeFile(o, path+"\\00_meta\\state.yml");
        }
        catch (FileNotFoundException ex)
        {
            ex.printStackTrace();
        }
        System.exit(0);
    }
    
    public static void updatePipeLine(String path,String res)
    {
        DumperOptions yamlOptions = new DumperOptions();
        yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
        Yaml y = new Yaml(yamlOptions);
        LinkedHashMap<String,Object> data = null;
        try
        {
            data = (LinkedHashMap<String,Object>) y.load(new FileInputStream(path+"\\00_meta\\state.yml"));
        }
        catch(IOException lm)
        {
        }
        if(data==null)
        {
            return;
        }
        String[] dirsExist = FileTK.getDirectoryContent(/*args[0]*/path,true);
        List<String[]> cmdQueue = new ArrayList<>();
        List<String> resultFiles = new ArrayList<>();
        List<String> packagesInitialized = (List<String>) data.get("HEAD");
        Arrays.stream(dirsExist).filter(t -> !t.startsWith("00_") && new File(path+"\\" + t).isDirectory()).forEach(t ->
        {
            if(!packagesInitialized.contains(t)&&FileTK.getDirectoryContent(path+"\\" + t+"\\proc").length>0) //package initialisiert sich erst wenn mindestens ein WP in proc
            {
                packagesInitialized.add(t);                           //vv-- highest IDX of package list aka current -> results in counter continuity
                Object[] rv = processPackage(/*args[0]+*/path+"\\" + t, packagesInitialized.size()-1, res);
                cmdQueue.addAll((List<String[]>) rv[0]);
                resultFiles.addAll((List<String>) rv[1]);
            }
        });
        

        //FileTK.writeFile(new Yaml().dump(cmdQueue),"T:\\wpc\\00_meta\\debug_.yaml");

        cmdQueue.forEach(x -> Tools.runCmdWithPassthru(System.out, x));



        String targetDir = (String) data.get("Outdir");
        resultFiles.forEach(entry -> 
        {
            String fn = FileTK.getFileName(entry);
            FileTK.kopierpaste(new File(entry),new File(targetDir+"\\"+fn));
        });
        data.put("HEAD", packagesInitialized);
        String o = y.dump(data);
        FileTK.writeFile(o, path+"\\00_meta\\state.yml");
        System.exit(0);

    }
    
    public static Object[] processPackage(String path,int packID,String res)
    {
        /*
        if(false)
        {
            System.out.println(packID+"|"+path);
            return;
        }*/
        System.out.println(path);
        FileTK.verzeichnisKillen(new File(path+"\\p"));
        new File(path+"\\p\\b\\").mkdirs();
        String[] availablePackagesNormal = FileTK.getDirectoryContent(path+"\\proc",true);
        String[] availablePackagesNoResize = FileTK.getDirectoryContent(path+"\\k-i-p",true);
        String[] availablePackagesBFrames = FileTK.getDirectoryContent(path+"\\b-frames",true);
        
        int c1 = availablePackagesNormal==null?0:availablePackagesNormal.length;
        int c2 = availablePackagesNoResize==null?0:availablePackagesNoResize.length;
        //System.out.println(c1+"|"+c2+"||"+(c1+c2));
        String[][] mergedList = new String[c1+c2][2];
        for (int i = 0; i < c1 ; i++)
        {
            mergedList[i][0] = availablePackagesNormal[i];
            mergedList[i][1] = "proc";
        }
        for (int i = 0; i < c2; i++)
        {
            mergedList[i+c1][0] = availablePackagesNoResize[i];
            mergedList[i+c1][1] = "k-i-p";
        }
                            //main inited_b's b_loop
        int[] cntr = new int[]{0,0,0};//HAX
        //Arrays.sort(mergedList, ); //verwursteln....
        List<String[]> commandQueue = new ArrayList<>();
        List<String> resultFiles = new ArrayList<>();
        Arrays.stream(mergedList).sorted((x, y) ->
        {
            return x[0].compareToIgnoreCase(y[0]);
        }).forEach((x) ->
        {
            String outFile = path + "\\p\\" + String.format("%04d", packID) + "_" + String.format("%04d", cntr[0]++);

            String[] y = x[1].equals("proc")
                    ? new String[]
                    {
                        "C:\\Program Files\\ImageMagick-6.8.8-Q16\\convert.exe", path + "\\" + x[1] + "\\" + x[0], "-resize", res + "!", outFile + ".jpg"
                    }
                    : new String[]
                    {
                        "C:\\Program Files\\ImageMagick-6.8.8-Q16\\convert.exe", path + "\\" + x[1] + "\\" + x[0], "-resize", res + ">", "-background", "black", "-gravity", "center", "-extent",res, outFile + ".jpg"
                    };
            resultFiles.add(outFile+ ".jpg");

            //System.out.println(Arrays.toString(y));
            if (cntr[0] % 5 == 0)
            {
                if (cntr[1] < availablePackagesBFrames.length)
                {
                    String bp = path+"\\p\\b\\"+cntr[1]+".jpg";
                    commandQueue.add(new String[]
                    {
                        "C:\\Program Files\\ImageMagick-6.8.8-Q16\\convert.exe", path + "\\b-frames\\" + availablePackagesBFrames[cntr[1]], "-resize", res + "!", bp
                    });
                    availablePackagesBFrames[cntr[1]]=bp;
                    cntr[1]++;
                }
                commandQueue.add(new String[]{"cmd.exe","/c","copy",availablePackagesBFrames[cntr[2]],outFile+"b.jpg"});
                cntr[2]=((cntr[2]+1)%availablePackagesBFrames.length);
                resultFiles.add(outFile+ "b.jpg");
            }
            commandQueue.add(y);
            
        }
        ); //System.out.println(packID+"|"+x[0])
        
        
        //DBG FileTK.writeFile(new Yaml().dump(commandQueue),"T:\\wpc\\00_meta\\debug_"+packID+".yaml");
        //normal
        //convert in.image -resize res! out.image
        
        //keepaspect's
        // res+">"
        
        
        //convert in.image -resize res+">" -background black -gravity center -extent res out.image
        return new Object[]{commandQueue,resultFiles};
    }
}
