import cocos
import pyglet

from maplayer import MapLayer
from itemlayer import ItemLayer
from player import Player
from note import Note
from npc import Npc
from policeman import Policeman
from dialogscene import DialogScene

class NoteLayer(cocos.layer.base_layers.Layer):

    def __init__(self):
        super(NoteLayer, self).__init__()
        note = cocos.sprite.Sprite('img/note.png')
        note.position = 300, 300

        self.label = cocos.text.Label(anchor_x = 'center',\
                                     anchor_y = 'center',\
                                     multiline=True,\
                                     width=300,position=(300,300),\
                                     color=(0,0,0,255),\
                                     font_name='Jenna Sue',\
                                     font_size=48)


        self.add(note, z=0)
        self.add(self.label, z=1)
        self.visible = False


class UILayer(cocos.layer.base_layers.Layer):

    is_event_handler = True

    def __init__(self):
        super(UILayer, self).__init__()

        gui = cocos.sprite.Sprite('img/ui.png')
        gui.position = 700,300

        self.ammo = cocos.sprite.Sprite('img/0.png')
        self.notes10 = cocos.sprite.Sprite('img/0.png')
        self.notes1 = cocos.sprite.Sprite('img/0.png')

        self.add(self.ammo, z=1)
        self.add(self.notes10, z=1)
        self.add(self.notes1, z=1)

        self.add(gui, z=0)

        self.note_count = 0

    def on_mouse_press(self, x, y, button, modifiers):
        pass

    def print_ammo(self, amount):
        self.remove(self.ammo)
        self.ammo = cocos.sprite.Sprite('img/'+str(amount)+'.png')
        self.ammo.position = 760, 240
        self.add(self.ammo, z=1)

    def print_notes(self):
        amount = self.note_count
        self.remove(self.notes10)
        self.remove(self.notes1)

        self.notes10 = cocos.sprite.Sprite('img/'+str(amount/10)+'.png')
        self.notes1 = cocos.sprite.Sprite('img/'+str(amount-(amount/10)*10)+'.png')

        self.notes10.position = 690, 50
        self.notes1.position = 710, 50

        self.add(self.notes10, z=1)
        self.add(self.notes1, z=1)



class GameScene(cocos.scene.Scene):

    def __init__(self):

        super(GameScene, self).__init__()

        self.map_layer = MapLayer()
        self.map_layer.generate_world(50,50)
        self.map_layer.set_view(0,0,600,600)

        self.note_layer = NoteLayer()

        self.ui_layer = UILayer()

        self.dialog_scene = None

        self.item_layer = ItemLayer(self.map_layer, self.note_layer, self.ui_layer)

        self.player = Player()
        self.player.set_pos(*self.map_layer.get_free_position(), force=True)
        self.player.add_to_layer(self.item_layer)
        self.ui_layer.print_ammo(self.player.ammo)
        self.item_layer.player = self.player
        self.item_layer.items[self.player.pos[0]][self.player.pos[1]].append(self.player)
        self.map_layer.center_view(*self.player.pos)
        self.item_layer.center_view(*self.player.pos)

        # Populating items

        # NPCs ---
        
        npcs = []
        for n in range(10):
            pos = self.map_layer.get_free_position()
            while self.item_layer.items[pos[0]][pos[1]] != []:
                pos = self.map_layer.get_free_position()

            npc = Npc(self.map_layer, self.item_layer)
            npc.set_pos(*pos)
            self.item_layer.items[pos[0]][pos[1]].append(npc)
            npc.add_to_layer(self.item_layer)
            npcs.append(npc)

        # The Target
        pos = self.map_layer.get_free_position()
        while self.item_layer.items[pos[0]][pos[1]] != []:
            pos = self.map_layer.get_free_position()

        npc = Npc(self.map_layer, self.item_layer)

        ok = True
        for n in npcs:
            if n == npc:
                ok = False
        while not ok:
            npc.randomize()
            ok = True
            for n in npcs:
                if n == npc:
                    ok = False           
        if ok:
            npc.set_pos(*pos)
            npc.is_target = True
            self.item_layer.items[pos[0]][pos[1]].append(npc)
            npc.add_to_layer(self.item_layer)
            npcs.append(npc)       


        # Notes ---
        colors = ['_black', '_grey']
        shapes1 = ['_npc1']
        shapes2 = ['_npc1', '_npc2']


        notes = []
        notes.append([True, 'color', npc.colors['hat'], 'hat'])
        notes.append([True, 'color', npc.colors['torso'], 'torso'])
        notes.append([True, 'color', npc.colors['legs'], 'legs'])
        notes.append([True, 'shape', npc.shapes['hat'], 'hat'])
        notes.append([True, 'shape', npc.shapes['torso'], 'torso'])
        notes.append([True, 'shape', npc.shapes['legs'], 'legs'])
        notes.append([True, 'shape', '_policeman', 'hat'])
        notes.append([True, 'shape', '_policeman', 'torso'])

        for k in colors:
            if k != npc.colors['hat']:
                notes.append([False, 'color', k, 'hat'])
            if k != npc.colors['torso']:
                notes.append([False, 'color', k, 'torso'])
            if k != npc.colors['legs']:
                notes.append([False, 'color', k, 'legs'])
        for k in shapes2:
            if k != npc.shapes['hat']:
                notes.append([False, 'shape', k, 'hat'])


        for n in notes:
            pos = self.map_layer.get_free_position()
            while self.item_layer.items[pos[0]][pos[1]] != []:
                pos = self.map_layer.get_free_position()

            note = Note('img/note_sprite.png', text='Testing ' + str(n))
            note.generate(n[0], n[1], n[2], n[3])
            note.pos = pos
            note.position = pos[0]*32+16, pos[1]*32+16
            self.item_layer.add(note, z=0)
            self.item_layer.items[pos[0]][pos[1]].append(note)

        for k in range(8):
            pos = self.map_layer.get_free_position()
            while self.item_layer.items[pos[0]][pos[1]] != []:
                pos = self.map_layer.get_free_position()

            note = Note('img/note_sprite.png', text='Testing ' + str(n))
            note.generate_info(k)
            note.pos = pos
            note.position = pos[0]*32+16, pos[1]*32+16
            notes.append(note)
            self.item_layer.add(note, z=0)
            self.item_layer.items[pos[0]][pos[1]].append(note)            


        # Policemen
        for n in range(7):
            pos = self.map_layer.get_free_position()
            while self.item_layer.items[pos[0]][pos[1]] != []:
                pos = self.map_layer.get_free_position()
            police = Policeman(self.map_layer, self.item_layer, self.player)
            police.set_pos(*pos, force=True)
            self.item_layer.items[pos[0]][pos[1]].append(police)
            police.add_to_layer(self.item_layer)



        self.item_layer.do_frame(self.player.pos)

        self.ui_layer.note_count = len(notes)
        self.ui_layer.print_notes()
        # Putting the layers into the scene
        self.add(self.map_layer, z=0)
        self.add(self.item_layer, z=1)
        self.add(self.note_layer, z=2)
        self.add(self.ui_layer, z=3)

        self.need_reset = True

        self.bgm = pyglet.media.load("snd/bgm.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.intro = True


    def on_enter(self):

        if self.intro:
            self.intro = False
            scene = DialogScene()
            dialog = [['??? :', '\"I need to focus.\"'],\
                      ['??? :', '\"My name...\"'],\
                      ['??? :', '\"Raoul. Raoul V.\"'],\
                      ['Raoul V. :', '\"I remember. I need to find someone.\"'],\
                      ['Raoul V. :', '\"And kill him.\"'],\
                      ['Raoul V. :', '\"But how to find him?\"'],\
                      ['Raoul V. :', '\"I scribbled some things but...\"'],\
                      ['Raoul V. :', '\"My notebook has been torn apart.\"'],\
                      ['Raoul V. :', '\"If I can find the pages, I will know.\"'],\
                      ['Raoul V. :', '\"Let\'s go!\"']\
                      ]
            scene.generate_dialogs(dialog)
            cocos.director.director.push(scene)

        #self.ui_layer.push_all_handlers()
        self.bgm_player.play()
        super(GameScene, self).on_enter()

        if self.item_layer.ending:
            self.need_reset = True
            cocos.director.director.pop()

        #if not self.need_reset:
        #    return

    def on_exit(self):
        pass
        self.bgm_player.pause()

        super(GameScene, self).on_exit()

        #self.ui_layer.remove_all_handlers()
