package com.gustavomaciel.enterprise;

import com.badlogic.gdx.utils.Array;
import com.gustavomaciel.enterprise.CollisionGroups.CollisionGroup;

/**
 * Created by Gustavo on 5/22/2016.
 */
public class CollisionResolver {
    public static void checkAndResolve(Array<Entity> entities) {
        for(int i = 0, s = entities.size; i < s; ++i) {
            Entity first = entities.get(i);
            if(first.isMarkedForDeletion() || first.isCollisionDisabled()) continue;
            for(int j = i+1; j < s; ++j) {
                Entity second = entities.get(j);
                if(second.isMarkedForDeletion() || second.isCollisionDisabled()) continue;
                check(first, second);
            }
        }
    }

    private static void check(Entity first, Entity second) {
        final CollisionGroup firstCG = first.getCollisionGroup();
        final CollisionGroup secondCG = second.getCollisionGroup();
        boolean firstInterested = firstCG.matches(secondCG);
        boolean secondInterested = secondCG.matches(firstCG);
        if(firstInterested || secondInterested) {
            if(first.position.x < second.position.x + second.size.x && first.position.x + first.size.x > second.position.x
            && first.position.y < second.position.y + second.size.y && first.position.y + first.size.y > second.position.y) {
                float intersectionX = 0.5f * (Math.max(first.position.x, second.position.x) + Math.min(first.position.x + first.size.x, second.position.x + second.size.x));
                float intersectionY = 0.5f * (Math.max(first.position.y, second.position.y) + Math.min(first.position.y + first.size.y, second.position.y + second.size.y));
                if(firstInterested) {
                    first.onCollision(second, intersectionX, intersectionY);
                }
                if(secondInterested) {
                    second.onCollision(first, intersectionX, intersectionY);
                }
            }
        }
    }
}
