import cocos
import pyglet

class SkipLayer(cocos.layer.Layer):
    is_event_handler = True
    def __init__(self):
        super(SkipLayer, self).__init__()

        self.dialogs = None
        self.layer = 0

    def on_key_press(self, key, modifier):
        if key == pyglet.window.key.ESCAPE:
            return True
        elif key == pyglet.window.key.SPACE:
            try:
                self.layer += 1
                self.dialogs.switch_to(self.layer)
            except:
                cocos.director.director.pop()
        elif key == pyglet.window.key.ENTER:
            cocos.director.director.pop()

class DialogScene(cocos.scene.Scene):

    def __init__(self):

        super(DialogScene, self).__init__()

        self.bg_layer = cocos.layer.Layer()
        self.titlecard = cocos.sprite.Sprite('img/titlecard.png')
        self.titlecard.position = 400,300
        self.bg_layer.add(self.titlecard)
        self.add(self.bg_layer)

        self.skip_layer = SkipLayer()
        self.add(self.skip_layer)

        self.bgm = pyglet.media.load("snd/bgm_dialog.ogg", streaming=True)
        self.bgm_player = pyglet.media.Player()
        self.bgm_player.queue(self.bgm)
        self.bgm_player.eos_action = self.bgm_player.EOS_LOOP

        self.final = False

    def generate_dialogs(self, dialogs):

        screens = []
        for d in dialogs:
            dialog = cocos.layer.Layer()
            if d[0] is not None:
                title_label = cocos.text.Label(anchor_x = 'center',font_name='Rechtman',position=(400,470), color=(255,255,255,255), font_size=40)
                title_label.element.text = d[0]
                dialog.add(title_label)

            text_label = cocos.text.Label(multiline=True, width=500, align='center', anchor_x='center',font_name='Rechtman',position=(400,300), color=(255,255,255,255), font_size=60)
            text_label.element.text = d[1]
            dialog.add(text_label)            
            screens.append(dialog)

        self.dialogs = cocos.layer.base_layers.MultiplexLayer(*screens)
        self.skip_layer.dialogs = self.dialogs
        self.skip_layer.layer = 0

        self.add(self.dialogs)

    def on_enter(self):
        self.bgm_player.play()
        super(DialogScene, self).on_enter()


    def on_exit(self):
        if self.final:
            cocos.director.director.terminate_app = True
        self.bgm_player.pause()
        super(DialogScene, self).on_exit()
