# L-36 MCS 260 Mon 11 Apr 2016 : frog_pond.py
"""
The pond stores a list of frogs and exports
function to help predators locate the frogs.
This class is needed for the eat() method in the Bird class.
First we define a useful function to compute the distance.
"""
from math import sqrt
from class_threadfrog import ThreadFrog

class FrogPond(object):
    """
    A pond keeps the frogs and allows
    to locate the frogs for predators.
    """
    def __init__(self, F):
        """
        F is a list of frogs,
        which may be empty at first.
        """
        self.frogs = F

    @staticmethod
    def distance(pnt, qnt):
        """
        Returns the distance between points pnt and qnt.
        """
        sqrdif = (pnt[0] - qnt[0])**2 + (pnt[1] - qnt[1])**2
        return sqrt(sqrdif)

    def nearest_frog(self, pos):
        """
        On input in pos is a tuple (x, y)
        with numerical coordinates in the plane.
        Returns (-1, None, -1) for an empty pond,
        or the tuple (d, f, i) where d is the
        distance of pos to the nearest frog
        at position i in the list of frogs.
        """
        if len(self.frogs) == 0:
            return (-1, None, -1)
        else:
            k = 0
            mindis = FrogPond.distance(self.frogs[k].position, pos)
            for i in range(1, len(self.frogs)):
                dis = FrogPond.distance(self.frogs[i].position, pos)
                if dis < mindis:
                    (k, mindis) = (i, dis)
            return (mindis, self.frogs[k], k)

def main():
    """
    Runs a test on the FrogPond class.
    """
    print('swamp with two frogs: a and b')
    ann = ThreadFrog('a', +10, +10, 5, 2, 4)
    bob = ThreadFrog('b', -10, -10, 15, 5, 3)
    swamp = FrogPond([ann, bob])
    while True:
        posraw = input("Give a tuple of coordinates : ")
        pos = eval(posraw)
        near = swamp.nearest_frog(pos)
        if near[0] != -1:
            print('nearest frog to', pos, 'is', \
            near[1].getName(), 'at distance', \
            near[0], 'at position', near[2])
        ans = input("more locations ? (y/n) ")
        if ans != 'y':
            break

if __name__ == "__main__":
    main()
