"""Imago intersections module"""

from math import cos, tan, pi
from operator import itemgetter

import ImageDraw

import k_means

def dst(line):
    """Return normalized line."""
    if line[0] < pi / 2:
        line = line[0] + pi, - line[1]
    return line

def dst_sort(lines):
    """Return lines sorted by distance."""
    l_max = max(l[0] for l in lines)
    l_min = min(l[0] for l in lines)
    if l_max - l_min > (3. / 4) * pi:
        lines = [dst(l) for l in lines]
    lines.sort(key=itemgetter(1))
    return lines

def board(image, lines, show_all, do_something):
    """Compute intersections, find stone colors and return board situation."""
    lines = [dst_sort(l) for l in lines]
    intersections = intersections_from_angl_dist(lines, image.size)

    if show_all:
        image_g = image.copy()
        draw = ImageDraw.Draw(image_g)
        for line in intersections:
            for (x, y) in line:
                draw.point((x , y), fill=(120, 255, 120))
        do_something(image_g, "intersections")

    board_raw = []
    
    for line in intersections:
        board_raw.append([stone_color_raw(image, intersection) for intersection in
                      line])
    board_raw = sum(board_raw, [])

    ### Show color distribution
    luma = [(0.30 * s[0] + 0.59 * s[1] + 0.11 * s[2]) / 255.
                 for s in board_raw]
    saturation = [(max(s) - min(s)) / (255 - abs(max(s) + min(s) - 255))
                 for s in board_raw]
    if show_all:
        import matplotlib.pyplot as pyplot
        pyplot.scatter(luma, saturation, color=[(s[0]/255., s[1]/255., s[2]/255., 1.) 
                                            for s in board_raw])
        pyplot.show()

    clusters = k_means.cluster(3, 2,zip(zip(luma, saturation), range(len(luma))),
                               [[0., 0.], [0.5, 0.25], [1., 0.5]])
   #clusters.sort(key=mean_luma)

    if show_all:
        pyplot.scatter([d[0][0] for d in clusters[0]], [d[0][1] for d in clusters[0]],
                                                 color=(1,0,0,1))
        pyplot.scatter([d[0][0] for d in clusters[1]], [d[0][1] for d in clusters[1]],
                                                 color=(0,1,0,1))
        pyplot.scatter([d[0][0] for d in clusters[2]], [d[0][1] for d in clusters[2]],
                                                 color=(0,0,1,1))
        pyplot.show()

    clusters[0] = [(p[1], 'B') for p in clusters[0]]
    clusters[1] = [(p[1], '.') for p in clusters[1]]
    clusters[2] = [(p[1], 'W') for p in clusters[2]]

    board_rl = sum(clusters, [])
    board_rl.sort()
    board_rg = (p[1] for p in board_rl)
    
    board_r = []

    try:
        for i in xrange(19):
            board_r.append([])
            for _ in xrange(19):
                board_r[i].append(board_rg.next())
    except StopIteration:
        pass

    return board_r

def mean_luma(cluster):
    return sum(c[0][0] for c in cluster) / float(len(cluster))

def intersections_from_angl_dist(lines, size, get_all=True):
    """Take grid-lines and size of the image. Return intersections."""
    intersections = []
    for (angl1, dist1) in lines[1]:
        line = []
        for (angl2, dist2) in lines[0]:
            if abs(angl1 - angl2) > 0.4:
                i_x =  (- ((dist2 / cos(angl2)) - (dist1 / cos(angl1))) 
                        / (tan(angl1) - tan(angl2)))
                i_y = (tan(angl1) * i_x) - (dist1 / cos(angl1))
                if get_all or (-size[0] / 2 < i_x < size[0] / 2 and 
                    -size[1] / 2 < i_y < size[1] / 2):
                    line.append((int(i_x + size[0] / 2),
                                 int(i_y + size[1] / 2)))
        intersections.append(line)
    return intersections
   
def stone_color_raw(image, (x, y)):
    """Given image and coordinates, return stone color."""
    suma = []
    for i in range(-2, 3):
        for j in range(-2, 3):
            try:
                suma.append(image.getpixel((x + i, y + j)))
            except IndexError:
                pass
    suma = (sum(s[0] for s in suma) / 25., sum(s[1] for s in suma) / 25., 
            sum(s[2] for s in suma) / 25.)
    return suma
