'use strict';

// The collision detection of SimplePhysicsEngine is a brute-force approach
class CollisionDetection {

    constructor(options) {
        this.options = Object.assign({
            COLLISION_DISTANCE: 28
        }, options);
        this.collisionPairs = {};
    }

    init(options) {
        this.gameEngine = options.gameEngine;
    }

    distance(o1, o2) {
        let dx = o2.x - o1.x;
        let dy = o2.y - o1.y;
        return Math.sqrt(dx * dx + dy * dy);
    }

    // check if pair (id1, id2) have collided
    checkPair(id1, id2) {
        if (id1 === id2) return;
        let o1 = this.gameEngine.world.objects[id1];
        let o2 = this.gameEngine.world.objects[id2];
        // make sure that objects actually exist. might have been destroyed
        if (!o1 || !o2) return;
        let pairId = [id1, id2].sort().join(',');

        if (this.distance(o1, o2) < this.options.COLLISION_DISTANCE) {
            if (!(pairId in this.collisionPairs)) {
                this.collisionPairs[pairId] = true;
                this.gameEngine.emit('collisionStart', { o1, o2 });
            }
        } else if (pairId in this.collisionPairs) {
            this.gameEngine.emit('collisionStop', { o1, o2 });
            delete this.collisionPairs[pairId];
        }
    }

    // detect by checking all pairs
    // TODO: loop below checks pair (i,j) as well as redundant (j,i)
    detect() {
        for (let o1 in this.gameEngine.world.objects)
            for (let o2 in this.gameEngine.world.objects)
                this.checkPair(o1, o2);
    }

}

module.exports = CollisionDetection;

@@ -567,47 +567,19 @@
     
-if (id1 === id2) return;%0A        let o1
+let objects
  = t
@@ -591,32 +591,58 @@
 ameEngine.world.
+objects;%0A        let o1 = 
 objects%5Bid1%5D;%0A  
@@ -656,38 +656,16 @@
 et o2 = 
-this.gameEngine.world.
 objects%5B
@@ -670,16 +670,17 @@
 s%5Bid2%5D;%0A
+%0A
         
@@ -815,15 +815,8 @@
 d2%5D.
-sort().
 join
@@ -1300,77 +1300,8 @@
 irs%0A
-    // TODO: loop below checks pair (i,j) as well as redundant (j,i)%0A
     
@@ -1323,22 +1323,21 @@
     
-for (let o1 in
+let objects =
  thi
@@ -1354,32 +1354,77 @@
 ne.world.objects
+;%0A        for (let k1 of Object.keys(objects)
 )%0A            fo
@@ -1434,44 +1434,34 @@
 let 
-o2 in this.gameEngine.world.
+k2 of Object.keys(
 objects)
 %0A   
@@ -1456,16 +1456,17 @@
 objects)
+)
 %0A       
@@ -1469,24 +1469,37 @@
             
+ if (k2 %3E k1)
  this.checkP
@@ -1502,21 +1502,21 @@
 eckPair(
-o1, o
+k1, k
 2);%0A    

make collision detection more efficent