import random

import pygame.image

from common.constants import GRID_CELL_SIZE, Direction
from common.helpers import parse_cord
from logic.health_bar import HealthBar


def load_knight_textures():
    random_index = random.randint(1, 4)
    states = [
        pygame.image.load(f'resources/textures/knight_{random_index}_up.png').convert_alpha(),  # up = 0
        pygame.image.load(f'resources/textures/knight_{random_index}_right.png').convert_alpha(),  # right = 1
        pygame.image.load(f'resources/textures/knight_{random_index}_down.png').convert_alpha(),  # down = 2
        pygame.image.load(f'resources/textures/knight_{random_index}_left.png').convert_alpha(),  # left = 3
    ]
    return states


class Knight(pygame.sprite.Sprite):

    def __init__(self, screen, position, group, team):
        super().__init__(group)

        self.direction = Direction.DOWN
        self.states = load_knight_textures()

        self.image = self.states[self.direction.value]
        self.position = position
        self._layer = 1
        position_in_px = (parse_cord(position[0]), parse_cord(position[1]))
        self.rect = self.image.get_rect(topleft=position_in_px)

        self.team = team
        self.max_hp = random.randint(7, 12)
        self.current_hp = random.randint(1, self.max_hp)
        self.attack = random.randint(4, 7)
        self.defense = random.randint(1, 4)
        self.points = 1
        self.health_bar = HealthBar(screen, self.rect, current_hp=self.current_hp, max_hp=self.max_hp, calculate_xy=True, calculate_size=True)

    def rotate_left(self):
        self.direction = self.direction.left()
        self.image = self.states[self.direction.value]

    def rotate_right(self):
        self.direction = self.direction.right()
        self.image = self.states[self.direction.value]

    def step_forward(self):
        if self.direction.name == 'UP':
            self.position = (self.position[0], self.position[1] - 1)
            self.rect.y = self.rect.y - GRID_CELL_SIZE - 5
        elif self.direction.name == 'RIGHT':
            self.position = (self.position[0] + 1, self.position[1])
            self.rect.x = self.rect.x + GRID_CELL_SIZE + 5
        elif self.direction.name == 'DOWN':
            self.position = (self.position[0], self.position[1] + 1)
            self.rect.y = self.rect.y + GRID_CELL_SIZE + 5
        elif self.direction.name == 'LEFT':
            self.position = (self.position[0] - 1, self.position[1])
            self.rect.x = self.rect.x - GRID_CELL_SIZE - 5

    def team_alias(self) -> str:
        return "k_b" if self.team == "blue" else "k_r"