import pygame
import src.resources as res


# A collision between two circles, true when occurs
def circle_collision(a_pos, b_pos, a_radius, b_radius):
    x1, y1 = a_pos
    x2, y2 = b_pos

    x = abs(x1 - x2)
    y = abs(y1 - y2)

    radius_sum = a_radius + b_radius
    # pythagorean triangle without square root
    if x*x+y*y <= radius_sum*radius_sum:
        return True

    return False


# Text Renderer
def text_format(message, text_font, text_size, text_color):
    new_font = res.font(text_font, text_size)
    new_text = new_font.render(message, 0, text_color)

    return new_text


def blit_rotate(surf, image, pos, origin_pos, angle):

    # calcaulate the axis aligned bounding box of the rotated image
    w, h = image.get_size()
    box = [pygame.math.Vector2(p) for p in [(0, 0), (w, 0), (w, -h), (0, -h)]]
    box_rotate = [p.rotate(angle) for p in box]
    min_box = (min(box_rotate, key=lambda p: p[0])[0], min(box_rotate, key=lambda p: p[1])[1])
    max_box = (max(box_rotate, key=lambda p: p[0])[0], max(box_rotate, key=lambda p: p[1])[1])

    # calculate the translation of the pivot
    pivot = pygame.math.Vector2(origin_pos[0], -origin_pos[1])
    pivot_rotate = pivot.rotate(angle)
    pivot_move = pivot_rotate - pivot

    # calculate the upper left origin of the rotated image
    origin = (pos[0] - origin_pos[0] + min_box[0] - pivot_move[0], pos[1] - origin_pos[1] - max_box[1] + pivot_move[1])

    # get a rotated image
    rotated_image = pygame.transform.rotate(image, angle)

    # rotate and blit the image
    return surf.blit(rotated_image, origin)

    # draw rectangle around the image
    #pygame.draw.rect (surf, (255, 0, 0), (*origin, *rotated_image.get_size()),2)
