from math import ceil

from direct.gui.OnscreenImage import OnscreenImage
from direct.showbase.DirectObject import DirectObject
from panda3d.core import TransparencyAttrib, Vec4
from people.player import instance as player
from people.player import MAX_HEALTH
from helper import STARS

from helper import base
from menu import menu


MAX_HEALTH_BAR_SIZE = 16*5
MAX_HEALTH_COLOR = Vec4(1, 1, 1, 1)
MIN_HEALTH_COLOR = Vec4(0.33, 0, 0, 1)
HEALTH_BAR_FG_COLOR = Vec4(0.8, 0.8, 0.8, 1)

stars_icons = [
    OnscreenImage(image='img/star_%s.png'%side, parent=base.pixel2d, scale=(16, 1, 16))
    for i in range(5) for side in ('left', 'right')
]
health_bar_pivot = base.pixel2d.attach_new_node('healthbar-pivot')
health_bar_bg = OnscreenImage(image='img/health_bar.png',
                              parent=health_bar_pivot, scale=(MAX_HEALTH_BAR_SIZE, 1, 16),
                              pos = (-MAX_HEALTH_BAR_SIZE, 1, 0))
health_bar = OnscreenImage(image='img/health_bar.png', parent=health_bar_pivot, scale=(1, 1, 16),
                           color=HEALTH_BAR_FG_COLOR)


def update_window(event):
    width = base.win.getXSize()
    height = base.win.getYSize()

    for i, icon in enumerate(stars_icons):
        icon.set_pos(width - (i//2)*32 - 32, 0, -64)
        icon.set_transparency(TransparencyAttrib.M_alpha)
    health_bar_pivot.set_pos(width - 16, 0, -32)
    menu.set_pos(width / 2, 0, -height / 2)


def update_display(task):
    health_perc = player.HP / MAX_HEALTH
    health_bar_width = ceil(MAX_HEALTH_BAR_SIZE * health_perc**2)
    health_bar.set_scale(health_bar_width, 1, 16)
    health_bar.set_x(-health_bar_width)
    health_bar_bg.set_color(
        MAX_HEALTH_COLOR * health_perc +
        MIN_HEALTH_COLOR * (1-health_perc))
    for i in range(10):
        if STARS[0] > i:
            stars_icons[i].show()
        else:
            stars_icons[i].hide()

    return task.cont

base.task_mgr.add(update_display)


class UI(DirectObject):
    def __init__(self):
        self.accept('window-event', update_window)


UI()
