package app.brest.utils.geometry;
/**
 * Created by François Gautrais on 16/08/16.
 * Support also GPS Shape (By using GPSPoint)
 */
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;

public class Shape  implements Serializable {
    protected ArrayList<Point> mPoints = new ArrayList<Point>();

    public Shape()
    {

    }

    public Shape(Point a)
    {
        mPoints.add(a);
    }

    public Shape(Point a, Point b)
    {
        mPoints.add(a);
        mPoints.add(b);
    }

    public Shape(Point a, Point b, Point c)
    {
        mPoints.add(a);
        mPoints.add(b);
        mPoints.add(c);
    }
    
    public void add(Point p)
    {
    	mPoints.add(p);
    }

    public boolean contains(Point p)
    {
        int nok=0;
        int nerr=0;
        for(int i=0; i<mPoints.size(); i++)
        {
            boolean ok=false;
            for(int j=0; j<mPoints.size()-2; j++)
            {
                int k=(j+1+i)%mPoints.size();
                int l=(j+2+i)%mPoints.size();
                ok=isInTriangle(mPoints.get(i), mPoints.get(k), mPoints.get(l), p);
                if(ok) break;
            }
            if(ok) nok++;
            else nerr++;
        }

        return (nok>0);
    }


    
    static boolean  moreOrLess(double a, double b)
    {
    	double marge = a>b?a/1000:b/1000;
    	double res = a - b;
    	if(res<0) res=-res;
    	return res<marge;
    }
    
    

    public static boolean isInTriangle(Point a, Point b, Point c, Point p)
    {
    		double A = getTriangleSurface (a,b,c);
    	 
    	   /* Calculate area of triangle PBC */  
    	   double A1 = getTriangleSurface (p,b, c);
    	   /* Calculate area of triangle PAC */  
    	   double A2 = getTriangleSurface (a, p, c);
    	 
    	   /* Calculate area of triangle PAB */   
    	   double A3 = getTriangleSurface (a, b, p);

    	   return moreOrLess(A ,A1 + A2 + A3);
    }
    public static double getTriangleSurface(Point a, Point b, Point c)
    {
        double A,B,C,p;
        A=a.getDistanceWith(b);
        B=b.getDistanceWith(c);
        C=c.getDistanceWith(a);
        p=(A+B+C)/2;

        return Math.sqrt(p*(p-A)*(p-B)*(p-C));
    }

    public JSONArray getJson()
    {
        JSONArray ar = new JSONArray();
        try {
            for(int i=0; i<mPoints.size(); i++)
            {
                JSONArray arr = new JSONArray();
                arr.put(mPoints.get(i).getY());
                arr.put(mPoints.get(i).getX());
                ar.put(arr);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return ar;
    }
}
