import sys, os
from direct.gui.DirectButton import DirectButton
from direct.gui.OnscreenImage import OnscreenImage
from functools import partial

from direct.gui.OnscreenText import OnscreenText
from direct.showbase.DirectObject import DirectObject

from world import instance as world
from global_stuff import base, button_style

background = OnscreenImage(image='img/title_screen.png', parent=base.render2d, pos=(0, 0, 0), scale=(1, 1, 1))

buttons = {}


def titlecase(s):
    return ' '.join(x.capitalize() or '_' for x in s.split('_'))


def select_level(filename):
    world().level = filename
    clear_buttons()
    background.hide()
    world().reset()
    base.messenger.send('level_selected')


def clear_buttons():
    for b in buttons.values():
        b.remove_node()
    buttons.clear()


def generate_buttons():

    x = [-1, 0, 1]
    xi = 0
    y = -0.1

    files = os.listdir('levels')
    files.sort()

    for filename in files:
        if filename[-2:] != '.l':
            continue
        buttons[filename] = DirectButton(text=filename[:-2], scale=.1,
                                         command=partial(select_level, filename),
                                         pos=(x[xi], 0, y))
        xi += 1
        if xi >= len(x):
            y -= 0.1
            xi = 0
    for b in buttons.values():
        button_style(b)


def show():
    background.show()
    generate_buttons()


class EventHandler(DirectObject):
    def __init__(self):
        self.accept('level_select', show)


EventHandler()

