import datetime

import pyglet as pyg
import pyglet.window.key as key
import pyglet.window.mouse as mouse

import cocos
from cocos.director import director

from .camera import camera
from .verkolst import verkolst
from . import keyboard_state, mouse_state


class CocostratUI(cocos.layer.Layer):
    is_event_handler = True

    def __init__(self):
        from .ui.status_bar import StatusBar
        from .ui.province_info import ProvinceInfo
        import app.ui.map_overlay as overlays
        super().__init__()
        self.province_info = ProvinceInfo()
        self.province_info.position = (director.window.width+450, director.window.height)
        self.add(self.province_info)
        # self.add_step_button()

        self.status_bar = StatusBar()
        self.add(self.status_bar)

        self.hl_province = None
        self.hl_province_sprite = cocos.sprite.Sprite('highlight_hex.png',
                                                      position=(100, 100))
        self.hl_province_sprite.visible = False

        from app.ui.overlay_layer import HexMapLayerWithOutlines
        self.overlay_layer = HexMapLayerWithOutlines('overlay', verkolst['overlay'])
        camera.add(self.overlay_layer)

        self.overlays = [
            overlays.FoodOverlay(self, self.overlay_layer),
            overlays.PopsOverlay(self, self.overlay_layer, 'lc'),
            overlays.PopsOverlay(self, self.overlay_layer, 'mc'),
            overlays.PopsOverlay(self, self.overlay_layer, 'uc'),
            overlays.TradeDistanceOverlay(self, self.overlay_layer),
        ]

        self.click_sound = pyg.media.load('assets/sound_effects/tap1.wav', streaming=False)
        self.knock_sound = pyg.media.load('assets/sound_effects/tap2.wav', streaming=False)

        self.on_turn_start()

    def on_turn_start(self):
        self.status_bar.on_turn_start()
        self.province_info.on_turn_start()
        for overlay in self.overlays:
            overlay.update()

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        if buttons & mouse.MIDDLE:
            x1, y1 = camera.screen_to_world(x-dx, y-dy)
            x2, y2 = camera.screen_to_world(x, y)
            d_world = (x2-x1, y2-y1)
            cam = camera.cam_position
            camera.cam_position = (cam[0] - d_world[0], cam[1] - d_world[1])

    def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
        if abs(scroll_y) == 1:
            camera.zoom(scroll_y)

    def on_mouse_press(self, x, y, buttons, modifiers):
        if buttons & mouse.LEFT:
            x, y = camera.screen_to_world(x, y)
            self.hl_province = verkolst['terrain'].get_at_pixel(x, y)
            if self.hl_province:
                self.click_sound.play()
                self.hl_province_sprite.position = self.hl_province.center
                self.hl_province_sprite.visible = True
            self.province_info.set_province(self.hl_province)
            for overlay in self.overlays:
                overlay.update()
        elif buttons & mouse.RIGHT:
            if self.hl_province is not None:
                self.knock_sound.play()
                self.hl_province = None
                self.hl_province_sprite.visible = False
                self.province_info.set_province(None)
                for overlay in self.overlays:
                    overlay.update()

    def toggle_overlay(self, overlay_idx):
        for idx, overlay in enumerate(self.overlays):
            if idx == overlay_idx:
                overlay.toggle()
            else:
                overlay.disable()
        self.overlay_layer.visible = any(overlay.enabled for overlay in self.overlays)

    def on_key_press(self, symbol, modifiers):
        if symbol == key.F1:
            verkolst.process_turn()
            self.on_turn_start()
        elif symbol == key.F2:
            self.toggle_overlay(0)
        elif symbol == key.F3:
            self.toggle_overlay(1)
        elif symbol == key.F4:
            self.toggle_overlay(2)
        elif symbol == key.F5:
            self.toggle_overlay(3)
        elif symbol == key.F6:
            self.toggle_overlay(4)


def main():
    from os.path import dirname, abspath, split, join
    import pyglet.image
    from pyglet import gl
    pyglet.image.Texture.default_mag_filter = gl.GL_NEAREST
    pyglet.image.Texture.default_min_filter = gl.GL_LINEAR

    # Must specify full path for Pycharm debugger to work... ugh
    base_dir = split(dirname(abspath(__file__)))[0]
    pyg.resource.path = [
        join(base_dir, 'assets/map/'),
        join(base_dir, 'assets/sprites/'),
        join(base_dir, 'assets/gui/'),
        join(base_dir, 'assets/sound_effects/')
    ]
    pyg.resource.reindex()
    # print(pyg.resource._default_loader._index)

    director.init(width=1920, height=1080, autoscale=True, resizable=True,
                  audio_backend='pyglet')
    director.window.push_handlers(keyboard_state)
    director.window.push_handlers(mouse_state)

    verkolst.init('Verkolst.tmx')

    camera.init()
    camera.add(verkolst['terrain'])
    camera.add(verkolst['rivers'])
    camera.add(verkolst['buildings'])
    # camera.add(verkolst['nations'])

    ui = CocostratUI()
    camera.overlay_layer.add(ui.hl_province_sprite)

    main_scene = cocos.scene.Scene(camera, ui)
    director.run(main_scene)


if __name__ == '__main__':
    main()

