/*
 * Copyright (C)2013 Gerald de Jong - GNU General Public License
 * please see the LICENSE.TXT in this distribution for more details.
 */

package eu.beautifulcode.eig.transform;

import eu.beautifulcode.eig.structure.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Gerald de Jong <geralddejong@gmail.com>
 */

public class Faces implements Mod {
    private Face faceA, faceB;
    private boolean flipped;

    public Faces(Face faceA, Face faceB) {
        this.faceA = faceA;
        this.faceB = faceB;
        flipped = faceA.order != faceB.order;
    }

    @Override
    public void apply(Fabric fabric, Mods mods, Mods after) {
        mods.remove(faceA);
        mods.remove(faceB);
        List<Pair> pairs = new ArrayList<Pair>();
        for (Joint a : faceA.joints) {
            List<Joint> bj = new ArrayList<Joint>(faceB.joints);
            Joint farB = null;
            double farQ = 0;
            for (Joint b : faceB.joints) {
                double q = a.loc.quadranceTo(b.loc);
                if (q > farQ) {
                    farQ = q;
                    farB = b;
                }
            }
            bj.remove(farB);
            int index0 = faceB.joints.indexOf(bj.get(0));
            int index1 = faceB.joints.indexOf(bj.get(1));
            if (index1 == (index0 + 1) % 3) {
                pairs.add(new Pair(bj.get(0), a));
                pairs.add(new Pair(a, bj.get(1)));
            }
            else {
                pairs.add(new Pair(bj.get(1), a));
                pairs.add(new Pair(a, bj.get(0)));
            }
        }
        for (Pair pair : pairs) mods.create(pair.a, pair.b, Role.RING);
        for (int i = 0; i < 6; i++) {
            Pair p1 = pairs.get(i);
            Pair p2 = pairs.get((i + 1) % pairs.size());
            Joint middle = p1.b;
            Joint aa = fabric.getBar(p1.a).getOther(p1.a);
            Joint bb = fabric.getBar(p2.b).getOther(p2.b);
            double ab = aa.loc.quadranceTo(middle.loc);
            double ba = bb.loc.quadranceTo(middle.loc);
            if (ab < ba) {
                mods.create(aa, middle, Role.CROSS);
            }
            else {
                mods.create(bb, middle, Role.CROSS);
            }
        }
        for (Interval side : faceA.getIntervals(fabric)) mods.remove(side);
        for (Interval side : faceB.getIntervals(fabric)) mods.remove(side);
    }

}