package csa.util;


import java.io.File;
import java.io.OutputStream;
import java.io.PrintStream;


/**
 */
public class Utility 
{
    public static String getCurrentStackTrace()
    {
        String s="";
        for (int i=0; i < Thread.currentThread().getStackTrace().length; i++)
        {
            s+=Thread.currentThread().getStackTrace()[i]+"\n";
        }
        return s;
    }

    static String add="";
    public static String getStackTrace(Throwable e)
    {
        add="";
         PrintStream  p= new PrintStream(
          new OutputStream()
          {
            @Override
            public void write( int b )
            {
                char[] c = {(char)b};
                String s = new String(c);
                add += s;
            }
          }
        );
        e.printStackTrace(p);
        p.flush();
        return add;
    }

    public static String makeRelative(String path)
    {
        File f = new File("."+File.separator);
        String here = f.getAbsolutePath();
        if (path.indexOf(here.substring(0,here.length()-1)) != -1)
        {
            path = path.substring(path.indexOf(here)+here.length());
            if (path.startsWith(File.separator))
            {
                path = path.substring(1);
            }
        }
        else
        {
            // c:\1\2\3\.
            // c:\1\2\blub\sound.wav

            int len = 1;
            while (here.regionMatches(0, path, 0, len)) len++;
            len -=2;
            if (len <= 1) return path;

            // go back to last File separator, dirs may have the same letters in front
            while ((!(path.substring(len).startsWith(File.separator))) && (len >=1)) len--;

            String rPath = path.substring(len+1);
            String rHere = here.substring(len+1);


            // 3\.
            // blub\sound.wav
            int up = UtilityString.countStrings(rHere, File.separator);
            for (int i=0; i< up; i++)
            {
                rPath = ".."+File.separator+rPath;
            }
            path = rPath;
        }
        return path;
    }

}
