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

import Image, ImageDraw

def board(image, lines, show_all, do_something):
    intersections = intersections_from_angl_dist(lines, image.size)
    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))

    if show_all:
        do_something(image_g, "intersections")

    board = []
    
    for line in intersections:
        board.append([stone_color(image, intersection) for intersection in
                      line])
    return board

def intersections_from_angl_dist(lines, size, get_all=False):
    intersections = []
    for (angl1, dist1) in sorted(lines[1], key=itemgetter(1)):
        line = []
        for (angl2, dist2) in sorted(lines[0], key=itemgetter(1)):
            if abs(angl1 - angl2) > 0.4:
                x =  - ((dist2 / cos(angl2)) - (dist1 / cos(angl1))) / (tan(angl1) - tan(angl2))
                y = (tan(angl1) * x) - (dist1 / cos(angl1))
                if get_all or (-size[0] / 2 < x < size[0] / 2 and 
                    -size[1] / 2 < y < size[1] / 2):
                    line.append((int(x + size[0] / 2), int(y + size[1] / 2)))
        intersections.append(line)
    return intersections
   
def stone_color(image, (x, y)):
    suma = 0.
    for i in range(-2, 3):
        for j in range(-2, 3):
            try:
                suma += sum(image.getpixel((x + i, y + j)))
            except IndexError:
                pass
    suma /= 3 * 25
    if suma < 55:
        return 'B'
    elif suma < 200: 
        return '.'
    else:
        return 'W'
