import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.io.*;
import java.util.Random;
import java.util.StringTokenizer;

/**
 * Created with IntelliJ IDEA.
 * User: Pavel Kunyavskiy
 * Date: 19/10/13
 * Time: 20:17
 */
public class CrossReverseGenerator implements PolygonGenerator{
    static void Reverse(int[] a, int l,int r){
        for (int i = l, j = r; i < j; i++, j--){
            int t = a[i];
            a[i] = a[j];
            a[j] = t;
        }
    }
    public static void fixSegmentIntersection(int[] x,int[] y){
        int n = x.length;
        assert x.length == y.length;

        boolean printed = false;
        while (true){
            boolean any = false;
            for (int i = 0; i < n; i++){
                if (x[i] == x[(i+1) % n] && y[i] == y[(i+1) % n]){
                    x[i] = x[i] + 1;
                    any = true;
                }
                for (int j = i + 2; j < n; j++)
                    if (!(i == 0 && j == n - 1) && SharedGeom.checkSegmentIntersection(
                            x[i], y[i], x[(i + 1) % n], y[(i + 1) % n],
                            x[j], y[j], x[(j + 1) % n], y[(j + 1) % n]
                    )) {
                        Reverse(x, i+1, j);
                        Reverse(y, i+1, j);
                        any = true;
//                        System.err.printf("(%d, %d) (%d, %d) (%d, %d) (%d, %d)\n", x[i], y[i], x[(i+1) % n], y[(i+1) % n], x[j], y[j], x[(j+1) % n], y[(j+1) % n]);
                    }
            }
            if (!any) break;
            if (!printed){
                System.err.println("Fixing intersections");
                printed = true;
            }
        }
        System.err.println("Fixed intersections");
    }
    public void generate(int[] x, int[] y, int maxCx, int maxCy, Random rnd){
        int n = x.length;
        assert x.length == y.length;
        for (int i = 0; i < n; i++){
            x[i] = rnd.nextInt(2*maxCx+1) - maxCx;
            y[i] = rnd.nextInt(2*maxCy+1) - maxCy;
        }
        fixSegmentIntersection(x, y);
    }
    public String Name(){
        return "Random broken line and intersection reverses";
    }

    public String shortName() {
        return "cross";
    }

}
