package tools;

import java.io.*;
import java.awt.geom.Point2D;
import java.net.*;
import java.io.FileNotFoundException;

/**
 * Created by IntelliJ IDEA.
 * User: Igor
 * Date: 29.11.2005
 * Time: 20:27:28
 * To change this template use File | Settings | File Templates.
 */
public class Tools
{
	public static String beforeFirst(String str, String ch)
	{
		int i=str.indexOf(ch);
		if(i!=-1)
		{
			return str.substring(0,i);
		}
		return "";
    }

	public static String afterFirst(String str, String ch)
	{
		int i=str.indexOf(ch);
		if(i!=-1)
		{
			return str.substring(i+ch.length());
		}
		return "";
    }
	
	public static String beforeLast(String str, String ch)
	{
		int i=str.lastIndexOf(ch);
		if(i!=-1)
		{
			return str.substring(0,i);
		}
		return "";
    }
	
	public static String afterLast(String str, String ch)
	{
		int i=str.lastIndexOf(ch);
		if(i!=-1)
		{
			return str.substring(i+ch.length());
		}
		return "";
    }
	
    /**
     * Чтение флоата совместимого с Delphi
     *
     * @param InStream
     * @return
     * @throws IOException
     */
    public static float readFloat(DataInputStream InStream) throws IOException
    {
        float f;
        int ch1, ch2, ch3, ch4, count;
        ch1 = InStream.readUnsignedByte();
        ch2 = InStream.readUnsignedByte();
        ch3 = InStream.readUnsignedByte();
        ch4 = InStream.readUnsignedByte();

        count = (ch4 << 24) | (ch3 << 16) | (ch2 << 8) | ch1;
        f = Float.intBitsToFloat(count);
        return f;
    }

    /**
     * запросить страицу с сервера
     *
     * @param strURL Адрес (php, html)
     * @return html страница
     */
    public static String getHTMLFromURL(String strURL)
    {
        String rez = null;
        String inputLine = null;
        try
        {
            rez = new String("".getBytes(), "utf-8");
            inputLine = new String("".getBytes(), "utf-8");
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        try
        {
            URL url = new URL(strURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x- www-form-urlencoded");
            DataOutputStream outwriter = new DataOutputStream(conn.getOutputStream());
            //outwriter.writeBytes(post);
            outwriter.flush();
            outwriter.close();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((inputLine = in.readLine()) != null)
            {
                rez += inputLine + "\n";
            }
            in.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return rez;
    }

    public static InputStream getHTMLFromURL2(String strURL)
    {
        String fileName = System.getProperty("java.io.tmpdir") + "tiptopcity.tmp";
        try
        {
            URL u = new URL(strURL);
            HttpURLConnection huc = (HttpURLConnection) u.openConnection();
            huc.setRequestMethod("GET");
            huc.connect();
            InputStream is = huc.getInputStream();
            int code = huc.getResponseCode();
            if (code == HttpURLConnection.HTTP_OK)
            {
                byte[] buffer = new byte[4096]; //4 Kb
                FileOutputStream outputStream = new FileOutputStream(new File(fileName));
                int bytes;
                while (true)
                {
                    bytes = is.read(buffer);
                    if (bytes <= 0) break;
                    outputStream.write(buffer, 0, bytes);
                }
                outputStream.close();
            }
            huc.disconnect();
        }
        catch (IOException e)
        {
            System.out.println("Exception\n" + e);
        }
        try
        {
            return new FileInputStream(new File(fileName));
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] getHTMLFromURL3(String strURL)
    {        
        URL u=null;
        try
        {
            u = new URL(strURL);
        } catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        return getHTMLFromURL3(u);
    }
    public static byte[] getHTMLFromURL3(URL u)
    {
        String fileName = System.getProperty("java.io.tmpdir") + "tiptopcity.tmp";
        try
        {
            HttpURLConnection huc = (HttpURLConnection) u.openConnection();
            huc.setRequestMethod("GET");
            huc.connect();
            InputStream is = huc.getInputStream();
            int code = huc.getResponseCode();
            if (code == HttpURLConnection.HTTP_OK)
            {
                byte[] buffer = new byte[4096]; //4 Kb
                FileOutputStream outputStream = new FileOutputStream(new File(fileName));
                int bytes;
                while (true)
                {
                    bytes = is.read(buffer);
                    if (bytes <= 0) break;
                    outputStream.write(buffer, 0, bytes);
                }
                outputStream.close();
            }
            huc.disconnect();
        }
        catch (IOException e)
        {
            System.out.println("Exception\n" + e);
        }

        try
        {
            return loadFileAsBytes(fileName);
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        return new byte[0];
    }
    //для передачи XML на сервер
    public static String getHTMLFromURL4(String u,String data)
    {
        String rez="";
        try {
            //String data = URLEncoder.encode("<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"0\" htmlid=\"0\" treeid=\"-1\"><filter></filter></metadata>", "UTF-8");
            byte[] mas=data.getBytes();
            URL url = new URL(u);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches (false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty( "User-Agent", "Mozilla/4.0" );
            conn.setRequestProperty( "Content-Type", "text/xml" );
            conn.setRequestProperty( "Content-Length", String.valueOf(mas.length));
            OutputStream wr = conn.getOutputStream();
            wr.write(mas);
            wr.flush();
            int rc = conn.getResponseCode();
            if(rc==200) // Get the response
            {
                String line="";
                BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while ((line = rd.readLine()) != null)
                {
                    rez += line;
                }
                rd.close();
            }
            wr.close();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return rez;
    }

    public static byte[] loadFileAsBytes(String fileName) throws IOException
    {
        return loadFileAsBytes(new File(fileName));
    }

    public static byte[] loadFileAsBytes(File file) throws IOException
    {
        byte[] result = new byte[(int) file.length()];
        loadFileAsBytes(file, result);
        return result;
    }

    public static void loadFileAsBytes(File file, byte[] buf) throws IOException
    {
        loadFileAsBytes(file, buf, 0, buf.length);
    }

    public static void loadFileAsBytes(File file, byte[] buf, int off, int len) throws IOException
    {
        FileInputStream f = new FileInputStream(file);
        try
        {
            f.read(buf, off, len);
        } finally
        {
            try
            {
                f.close();
            } catch (Exception e)
            {
            }
        }
    }

    public static String loadFileAsString(File file, String encoding) throws IOException
    {
        InputStreamReader f = encoding == null ? new FileReader(file) :
                new InputStreamReader(new FileInputStream(file), encoding);
        StringBuffer sb = new StringBuffer();
        try
        {
            char[] buf = new char[32768];
            int len;
            while ((len = f.read(buf, 0, buf.length)) >= 0)
            {
                sb.append(buf, 0, len);
            }
            return sb.toString();
        } finally
        {
            try
            {
                f.close();
            } catch (Exception e)
            {
            }
            ;
        }
    }

    public static String loadFileAsString(String fileName, String encoding)throws IOException
    {
        return loadFileAsString(new File(fileName), encoding);
    }

    public static char[] loadFileAsChars(String fileName, String encoding) throws IOException
    {
        return loadFileAsChars(new File(fileName), encoding);
    }

    public static char[] loadFileAsChars(File file, String encoding) throws IOException
    {
        String buf = loadFileAsString(file, encoding);
        char[] result = new char[buf.length()];
        buf.getChars(0, result.length, result, 0);
        return result;
    }


    public static void loadFileAsChars(File file, String encoding, char[] buf) throws IOException
    {
        loadFileAsChars(file, encoding, buf, 0, buf.length);
    }


    public static void loadFileAsChars(File file, String encoding,char[] buf, int off, int len) throws IOException
    {
        InputStreamReader f = encoding == null ?
                new FileReader(file) :
                new InputStreamReader(
                        new FileInputStream(file), encoding);
        try
        {
            f.read(buf, off, len);

        } finally
        {
            try
            {
                f.close();
            } catch (Exception e)
            {
            };
        }
    }

    public static void saveFileFromString(String fileName, String encoding, String v) throws IOException
    {
        saveFileFromString(new File(fileName), encoding, v);
    }


    public static void saveFileFromString(File file, String encoding, String v) throws IOException
    {
        if (v == null)
        {
            file.delete();
            return;
        }
        char[] buf = new char[v.length()];
        v.getChars(0, buf.length, buf, 0);
        saveFileFromChars(file, encoding, buf);
    }


    public static void saveFileFromChars( String fileName, String encoding, char[] buf) throws IOException
    {
        saveFileFromChars(new File(fileName), encoding, buf);
    }


    public static void saveFileFromChars(File file, String encoding, char[] buf) throws IOException
    {
        if (buf == null)
        {
            file.delete();
            return;
        }
        saveFileFromChars(file, encoding, buf, 0, buf.length);
    }


    public static void saveFileFromChars(File file, String encoding, char[] buf, int off, int len) throws IOException
    {
        if (buf == null)
        {
            file.delete();
            return;
        }
        OutputStreamWriter f = encoding == null ?  new FileWriter(file) : new OutputStreamWriter(new FileOutputStream(file), encoding);
        try
        {
            f.write(buf, off, len);
        } catch (IOException e)
        {
            try
            {
                f.close();
            } catch (Exception e1)
            {
            }
            ;
            return;
        }
        f.close();
    }

    /**
     * Чтение Integera совместимого с delphi
     *
     * @param InStream
     * @return
     * @throws IOException
     */
    public static int readInt(DataInputStream InStream) throws IOException
    {
        int ch1, ch2, ch3, ch4, count;
        ch1 = InStream.readUnsignedByte();
        ch2 = InStream.readUnsignedByte();
        ch3 = InStream.readUnsignedByte();
        ch4 = InStream.readUnsignedByte();

        count = (ch4 << 24) | (ch3 << 16) | (ch2 << 8) | ch1;
        return count;
    }

    /**
     * Чтение ASCI строки из файла знак конца строки #0
     *
     * @param InStream
     * @param i
     * @return
     * @throws IOException
     */
    public static String readString(DataInputStream InStream, int i) throws IOException
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int ch;
        while (true)
        {
            ch = InStream.readUnsignedByte();
            //System.out.println(ch);
            ch = ch ^ i; //вот это надо будет потом удалить
            //System.out.println("xor="+ch);
            if (ch == 0) break;
            baos.write(ch);
        }
        return baos.toString();
    }

    /**
     * Вернуть расширение файла
     *
     * @return расширение
     */
    public static String getExpansion(String fileName)
    {
        String exp = "";
        for (int i = fileName.length() - 1; i > 0; i--)
        {
            if (fileName.charAt(i) == '.')
            {
                break;
            } else
            {
                exp = fileName.charAt(i) + exp;
            }
        }
        return exp;
    }

    /**
     * Вернуть название файла
     *
     * @param path - путь
     * @return
     */
    public static String getFileName(String path)
    {
        path = path.replace('\\', '/');
        int lastSep = path.lastIndexOf('/');
        return path.substring(lastSep + 1);
    }

    //узнать точку пересичений 2х линай если x=0 и y=0 то не пересиклась
    public static Point2D.Float getCrossingLine(Point2D.Float PHead0, Point2D.Float PTail0, Point2D.Float PHead1, Point2D.Float PTail1)
    {
        Point2D.Float rezPoint = new Point2D.Float();

        float a0, b0, c0, a1, b1, c1;
        boolean bRez = true;
        a0 = PTail0.y - PHead0.y;
        b0 = PHead0.x - PTail0.x;
        c0 = PTail0.x * PHead0.y - PHead0.x * PTail0.y;

        a1 = PTail1.y - PHead1.y;
        b1 = PHead1.x - PTail1.x;
        c1 = PTail1.x * PHead1.y - PHead1.x * PTail1.y;

        if (b1 == 0) rezPoint.x = PHead1.x;//если перпендикулярна oy
        else rezPoint.x = (-(b0 * c1 / b1) + c0) / ((b0 * a1 / b1) - a0);
        if (a1 == 0) rezPoint.y = PHead1.y;//если перпендикулярна oy
        else rezPoint.y = (-(c1 * a0 / a1) + c0) / ((a0 * b1 / a1) - b0);
        //проверка на вхождение в отрезоки (с погрешностью 0.0000001)
        //по x
        if ((rezPoint.x < Math.min(PHead0.x, PTail0.x) - 0.0000001) || (rezPoint.x > Math.max(PHead0.x, PTail0.x) + 0.0000001))
            bRez = false;
        if ((rezPoint.x < Math.min(PHead1.x, PTail1.x) - 0.0000001) || (rezPoint.x > Math.max(PHead1.x, PTail1.x) + 0.0000001))
            bRez = false;
        //по y
        if ((rezPoint.y < Math.min(PHead0.y, PTail0.y) - 0.0000001) || (rezPoint.y > Math.max(PHead0.y, PTail0.y) + 0.0000001))
            bRez = false;
        if ((rezPoint.y < Math.min(PHead1.y, PTail1.y) - 0.0000001) || (rezPoint.y > Math.max(PHead1.y, PTail1.y) + 0.0000001))
            bRez = false;

        if (!bRez)
        {
            rezPoint.x = 0;
            rezPoint.y = 0;
        }
        return rezPoint;
    }

    public class Triangle
    {
        int a,b,c;
    }


    public static float getLength(Point2D point1, Point2D point2)
    {
        return (float) Math.sqrt((point1.getX() - point2.getX()) * (point1.getX() - point2.getX()) + (point1.getY() - point2.getY()) * (point1.getY() - point2.getY()));
    }
    
    /**
    * узнать градус точки относительно заданного центра(радианы)}
    */
    public static double getAngle(Point2D.Float CenterPoint,Point2D.Float ResearchedPoint)
    {
        double A, B, C, Angle;
        Angle = 0;
        A = (Math.abs(ResearchedPoint.y - CenterPoint.y) * 1.0); // А И В катеты треугольника
        B = (Math.abs(ResearchedPoint.x - CenterPoint.x) * 1.0);
        C = Math.sqrt(A * A + B * B);   // С гипотенуза треугольника
        if (C > 0)
        {
            Angle = Math.asin(B / C);

            if ((ResearchedPoint.x > CenterPoint.x) && (ResearchedPoint.y >= CenterPoint.y)) Angle =  Math.PI/2 - Angle;
            else //попрвка на сектора
                if ((ResearchedPoint.x <= CenterPoint.x) && (ResearchedPoint.y > CenterPoint.y))
                    Angle = Math.PI/2.0 + Angle;
                else//попрвка на сектора
                    if ((ResearchedPoint.x < CenterPoint.x) && (ResearchedPoint.y <= CenterPoint.y))
                        Angle = 3.0/2.0*Math.PI - Angle;
                    else//попрвка на сектора
                        if ((ResearchedPoint.x >= CenterPoint.x) && (ResearchedPoint.y < CenterPoint.y))
                            Angle = 3.0 / 2.0 * Math.PI + Angle;//попрвка на сектора
        }
        return Angle;
    }

    //узнать уравнение окружности проходящей через 3 точки
    public static Circle fnCalcCircle(Point2D.Float p1, Point2D.Float p2, Point2D.Float p3)
    {
        Circle сircle=new Circle();
        float a1, b1, a2, b2, c1, c2;
        float k1, k2;
        a1 = 2 * (p1.x - p2.x);
        b1 = 2 * (p2.y - p1.y);
        c1 = ((p2.y - p1.y) * p2.y + (p2.y - p1.y) * p1.y) - ((p1.x - p2.x) * p1.x + (p1.x - p2.x) * p2.x);
        a2 = 2 * (p3.x - p2.x);
        b2 = 2 * (p2.y - p3.y);
        c2 = ((p2.y - p3.y) * p2.y + (p2.y - p3.y) * p3.y) - ((p3.x - p2.x) * p3.x + (p3.x - p2.x) * p2.x);
        if (b1 != 0)
        {
            k1 = (b2 * a1) / b1 - a2;
            if (k1 == 0) //3 точки в 1 линии
            {
                сircle.r = 0;
                return сircle;
            }
            сircle.cnt.x = ((c2 - (b2 * c1) / b1) / k1);
            сircle.cnt.y = (c1 + a1 * сircle.cnt.x) / b1;
        } else if (b2 != 0)
        {
            k2 = (b1 * a2) / b2 - a1;
            if (k2 == 0) //3 точки в 1 линии
            {
                сircle.r = 0;
                return сircle;
            }
            сircle.cnt.x = (c1 - (b1 * c2) / b2) / k2;
            сircle.cnt.y = (c2 + a2 * сircle.cnt.x) / b2;
        } else
        { //всё в ё точке
            сircle.r = 0;
        }
        сircle.r = (float) Math.sqrt((сircle.cnt.x - p1.x) * (сircle.cnt.x - p1.x) + (сircle.cnt.y - p1.y) * (сircle.cnt.y - p1.y));
        return сircle;
    }
    
}
