from __future__ import annotations

import attrs
import tcod.console
import tcod.constants
import tcod.event
from tcod.event import KeySym

import g
import game.world_tools
from game.components import Gold, Graphic, Position
from game.constants import DIRECTION_KEYS, ACTION_KEYS
from game.state import Push, State, StateResult
from game.tags import IsItem, IsPlayer, IsDoor, IsActor
from game.constants import WALL_CHAR
from game.states import MainMenu


@attrs.define()
class InGame(State):
    """Primary in-game state."""

    def on_event(self, event: tcod.event.Event) -> StateResult:
        """Handle events for the in-game state."""
        (player,) = g.world.Q.all_of(tags=[IsPlayer])
        match event:
            case tcod.event.KeyDown(sym=sym) if sym in ACTION_KEYS:
                for door in g.world.Q.all_of(tags=[IsDoor]):
                    if (player.components[Position] - door.components[Position]).length() < 2:
                        ACTION_KEYS[sym](door)
            case tcod.event.Quit():
                raise SystemExit()
            case tcod.event.KeyDown(sym=sym) if sym in DIRECTION_KEYS:
                new_pos = player.components[Position] + DIRECTION_KEYS[sym]
                if not g.world_map.walkable[g.world_center.y+new_pos.y][g.world_center.x+new_pos.x]:
                    return None
                player.components[Position] = new_pos
                # Auto pickup gold
                for gold in g.world.Q.all_of(components=[Gold], tags=[player.components[Position], IsItem]):
                    player.components[Gold] += gold.components[Gold]
                    text = f"Picked up {gold.components[Gold]}g, total: {player.components[Gold]}g"
                    g.world[None].components[("Text", str)] = text
                    gold.clear()
                return None
            case tcod.event.KeyDown(sym=KeySym.ESCAPE):
                return Push(MainMenu())
            case _:
                return None

    def on_draw(self, console: tcod.console.Console) -> None:
        """Draw the standard screen."""
        centers = [a.components[Position] for a in g.world.Q.all_of(tags=[IsPlayer])]
        camera_pos = sum(centers, start=Position(0,0))
        camera_pos = camera_pos.mod(len(centers))
        h = console.height//2
        w = console.width//2
        def draw(e_pos, e_graph):
            screen_pos = e_pos - camera_pos
            if (-w <= screen_pos.x < w\
                and -h <= screen_pos.y < h):
                graphic = e_graph
                console.rgb[["ch", "fg"]][screen_pos.y + h, screen_pos.x + w] = graphic.ch, graphic.fg
        for (y, row) in enumerate(g.world_map.walkable):
            for (x, val) in enumerate(row):
                if not val:
                    draw(Position(x,y)-g.world_center, Graphic(WALL_CHAR))
        for entity in g.world.Q.all_of(components=[Position, Graphic]).none_of(tags=[IsActor]):
            draw(entity.components[Position], entity.components[Graphic])
        for actor in g.world.Q.all_of(components=[Position, Graphic], tags=[IsActor]).none_of(tags=[IsPlayer]):
            draw(actor.components[Position], entity.components[Graphic])
        for player in g.world.Q.all_of(tags=[IsPlayer]):
            draw(player.components[Position], player.components[Graphic])
        if text := g.world[None].components.get(("Text", str)):
            console.print(x=0, y=console.height - 1, string=text, fg=(255, 255, 255), bg=(0, 0, 0))
