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

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Map;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JTextArea;

/**
 *
 * @author LH
 */
public class sfxMain
{
    public static void main(String args[])
    {
        try
        {
            //String path = processEnvVarsinLine("%temp%/iZunpaq");
            
            String path2 = sfxMain.class.getProtectionDomain().getCodeSource().getLocation().getPath();
            String decodedPath = URLDecoder.decode(path2, "UTF-8");
            System.out.println(decodedPath);
            IZPackage izp = new IZPackage(decodedPath);
            String[] content = izp.getFileList();
            boolean gotparamfile=false;
            boolean installer = false;
            boolean portableapp=false;
            for (String string : content)
            {
                if(string.equals("params.sfx"))
                {
                    gotparamfile=true;
                }
                if(string.equals("sfx.bat"))
                {
                    installer=true;
                }
                if(string.equalsIgnoreCase("portableapp"))
                {
                    portableapp=true;
                }
            }
            String path = FileTK.getFilePath(decodedPath);
            if(portableapp)
            {
                path=processEnvVarsinLine("%temp%\\"+new File(decodedPath).getName());
            }
            String execafterXTract="";
            if(gotparamfile)
            {
                execafterXTract = replaceHashmarkedVars(izp.getFileContent("params.sfx"), "path", path);
                execafterXTract = replaceHashmarkedVars(execafterXTract, "sfxjar", decodedPath);
            }
            izp.unload();
            IZPackage.ExtractFilesToPath(decodedPath, path);
            if(gotparamfile)
            {
                FileTK.writeFile(execafterXTract,path+File.separator+"sfx.bat");
                runSingleCmd(path+File.separator+"sfx.bat");
            }
            else
            {
                if(installer)runSingleCmd(path+File.separator+"sfx.bat");
            }
            //exec
        }
        catch (UnsupportedEncodingException ex)
        {
            
            ex.printStackTrace();
        }
        
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    public static String replaceHashmarkedVars(String line,String varname,String toReplace)
    {
        System.out.println("in: "+line);
        String linemod = line;
        int varstart = linemod.indexOf("#");
        int varend = linemod.indexOf("#", varstart + 1);
        String preVar = "";
        if (varstart == -1||varend == -1)
        {
            System.out.println("NullVar");
            return line;
        }
        if (varstart > 0)
        {
            preVar = linemod.substring(0, varstart);
        }
        String postVar = linemod.substring(varend + 1);
        String var = linemod.substring(varstart + 1, varend);
        System.out.println("davor: "+varstart);
        System.out.println("var: "+var);
        System.out.println("ende: "+varend);
        if(var.equalsIgnoreCase(varname))
        {
            System.out.println("recurseNormal");
            var = toReplace;
            postVar=replaceHashmarkedVars(postVar, varname, toReplace);//falls sich noch wo anders eine versteckt
        }
        else
        {
            System.out.println("recurseOther");
            var="#"+var+"#";
            postVar=replaceHashmarkedVars(postVar, varname, toReplace);//falls sich noch wo anders eine versteckt
        }
        line = preVar + var + postVar;
        System.out.println("Retval"+line);
        return line;
    }
    
    public static String processEnvVarsinLine(String line)
    {
        Map<String, String> env = System.getenv();
        String linemod = line;
        int varstart = linemod.indexOf("%");
        int varend = linemod.indexOf("%", varstart + 1);
        String preVar = "";
        if (varstart == -1)
        {
            return line;
        }
        if (varstart > 0)
        {
            preVar = linemod.substring(0, varstart);
        }
        String postVar = linemod.substring(varend + 1);
        String var = linemod.substring(varstart + 1, varend);
        var = env.get(var.toUpperCase());
        line = preVar + var + postVar;
        return line;
    }
    
    public static String FileChooseDlg(javax.swing.JFrame frm)
    {
        return FileChooseDlg(frm,false,false,null);
    }
    
    public static String FileChooseDlg(javax.swing.JFrame frm,boolean restrict,boolean dirsOnly,String[] exts)
    {
        JFileChooser fc = new JFileChooser();
        String ret = "";
        //fc.
        if(!dirsOnly)
            fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        else
            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        if(restrict)
        {
            FIleLImiter f = new FIleLImiter();
            f.setExtensions(exts);
            fc.setFileFilter(f);
        }
        int returnVal = fc.showOpenDialog(frm);
        if (returnVal == JFileChooser.APPROVE_OPTION)
        {
            File file = fc.getSelectedFile();
            try
            {
                //This is where a real application would open the file.
                ret = file.getCanonicalPath();
            }
            catch (IOException ex)
            {
            }
        }
        return ret;
        //log.setCaretPosition(log.getDocument().getLength());
    }    
        
        
    public static void runSingleCmd(String... runnable)
    {
        runSingleCmd(true, runnable);
    }

    public static void runSingleCmd(boolean logg, String... runnable)
    {
        runSingleCmd(true, false, runnable);
    }

    public static void runSingleCmd(boolean logg, boolean legacy, String... runnable)
    {
        runSingleCmd(logg, legacy, false, runnable);
    }

    

    
    
    public static String runSingleCmd(boolean logg, boolean legacy, boolean sret, String... runnable)
    {
        return runSingleCmd(logg, legacy, sret, null, runnable);
    }

    public static String runSingleCmd(boolean logg, boolean legacy, boolean sret,JTextArea tx, String... runnable)
    {
    return runSingleCmd(logg, legacy, sret, false, tx, runnable);
    }
    public static String runSingleCmd(boolean logg, boolean legacy, boolean sret,boolean asArray,JTextArea tx, String... runnable)
    {
        return runSingleCmd(logg, legacy, sret, asArray, tx, null, runnable);
    }
    
    private static Process p;
    public static String runSingleCmd(boolean logg, boolean legacy, boolean sret,boolean asArray,final JTextArea tx, final PrintStream pw, String... runnable)
    {
        boolean execCrashed = false;
                String cret = "";
        //String rn = runnable[0];
        //String[]temp = runnable[0].split("\\.");
        /*if("bat".equals(temp[temp.length-1]))
         {
            
         runnable[0] = "cmd.exe";
         runnable[1] = "/c";
         runnable[2] = "\"\""+rn+"\" \"";
         }*/
        //else
        //{
        //String[] r2 = runnable;
        //}
        String cmd = "";
        if(!asArray)
        {
            for (String string : runnable)
            {
                cmd += string + " ";
                cmd = cmd.trim();

            }
        }
        try
        {
            {
                p = null;
                if(!asArray)
                    p=Runtime.getRuntime().exec(cmd);
                else
                    p=Runtime.getRuntime().exec(runnable);
                if(tx!=null)
                {
                    new Thread(
                    new Runnable()
                    {

                        @Override
                        public void run()
                        {
                        Scanner scanner = new Scanner(p.getInputStream());
                        Scanner scannerE = new Scanner(p.getErrorStream());
                        while ((scanner.hasNextLine()||scannerE.hasNextLine()))
                        {
                            if(scanner.hasNextLine())
                            {
                                String l = scanner.nextLine();
                                tx.append(l+"\n");
                                if(pw!=null)
                                    pw.println(l);
                            }
                            if(scannerE.hasNextLine())
                            {
                                String l = scannerE.nextLine();
                                tx.append(l+"\n");
                                if(pw!=null)
                                    pw.println(l);
                            }
                        }
                    }
                }
            ).start();
                }
                if (sret)
                {
                    cret = new BufferedReader(new InputStreamReader(p.getInputStream())).readLine();
                }
                int rv = p.waitFor();
                if(rv>0)
                {
                    execCrashed=true;
                }
            }
        }
        catch (Exception ex)
        {
            //TODO:SetupError_Here
            //Logger.getLogger(Tools.class.getName()).log(Level.SEVERE, null, ex);
        }
        return cret;
    }
        
        
        
        
        
        
        
        
        
        
    
    
    
}
