import pygame
import core.image_loader as image_loader
import core.item_settings as item_settings

class Hotbar:
    def __init__(self, items, screen_size):
        self.items = items
        self.rect = pygame.Rect(0, screen_size[1]-100, screen_size[0], 100)
        self.selected_item = None
        self.selected_item_count = 0
        self.selected_item_type = None
        self.mine_power = 0
        self.item_images = image_loader.item_images

    def draw(self, screen, font, small_font):
        surface = pygame.Surface(self.rect.size)
        surface.set_alpha(200)
        surface.fill((150, 100, 40))
        screen.blit(surface, self.rect)
        for i, (item, count) in enumerate(self.items.items()):
            pos = [self.rect.x + 20 + 70*i, self.rect.y+10]
            rect = pygame.Rect(pos[0], pos[1], 64, 64)
            screen.blit(self.item_images[item], pos)
            screen.blit(font.render(str(count), True, (255, 255, 255)), (pos[0], pos[1]+20))
            pygame.draw.rect(screen, (150, 150, 150), (self.rect.x + 20 + 70 * i, self.rect.y + 10, 64, 64), 3)
            if item == self.selected_item:
                pygame.draw.rect(screen, (255, 255, 255), (pos[0], pos[1], 64, 64), 3)
                self.selected_item_count = count
            if pygame.key.get_pressed()[pygame.K_LCTRL] and rect.collidepoint(pygame.mouse.get_pos()):
                surface = pygame.Surface((64, 48))
                surface.set_alpha(210)
                surface.fill((150, 100, 40))
                screen.blit(surface, (pos[0], pos[1]-48))
                screen.blit(small_font.render(str(item_settings.item_type_settings[item]), True, (0, 0, 0)), (pos[0]+3, pos[1]-45))
                screen.blit(small_font.render(str(item_settings.item_power_settings[item]), True, (0, 0, 0)), (pos[0]+3, pos[1]-20))

    def handle_event(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            if self.rect.collidepoint(event.pos):
                for i, (item, count) in enumerate(self.items.items()):
                    rect = pygame.Rect(self.rect.x + 20 + i*70, self.rect.y+10, 64, 64)
                    if rect.collidepoint(event.pos):
                        self.selected_item = item
                        self.selected_item_count = count

                return True
        return False

    def update_mine_power(self):
        self.mine_power = 0
        if self.selected_item is not None:
            self.mine_power = item_settings.item_power_settings[self.selected_item]

    def update_items(self):
        new_items = self.items.copy()
        for item, count in self.items.items():
            if count <= 0:
                del new_items[item]
        self.items = new_items

    def update_item_type(self):
        self.selected_item_type = None
        if self.selected_item is not None:
            self.selected_item_type = item_settings.item_type_settings[self.selected_item]