"""Functions for working with worlds."""

from __future__ import annotations

from random import Random

import g

from tcod.ecs import Registry, Entity
from tcod.map import Map

from game.components import Gold, Graphic, Position
from game.tags import IsActor, IsItem, IsPlayer, IsDoor

def add_wall(pos, remove=False):
    r_pos = g.world_center + pos
    g.world_map.walkable[r_pos.y][r_pos.x] = remove

def add_door(pos):
    door = g.world[object()]
    door.tags.add(IsDoor)
    door.components[Position] = pos
    door.components[Graphic] = Graphic(ord("\\"))
    add_wall(pos)


def new_world() -> Registry:
    """Return a freshly generated world."""
    world = Registry()
    g.world = world
    g.world_map = Map(100, 100)
    g.world_map.walkable[:] = True
    rng = world[None].components[Random] = Random()

    player = world[object()]
    player.components[Position] = Position(5, 5)
    player.components[Graphic] = Graphic(ord("@"))
    player.components[Gold] = 0
    player.tags |= {IsPlayer, IsActor}

    for _ in range(10):
        gold = world[object()]
        gold.components[Position] = Position(rng.randint(0, 20), rng.randint(0, 20))
        gold.components[Graphic] = Graphic(ord("$"), fg=(255, 255, 0))
        gold.components[Gold] = rng.randint(1, 10)
        gold.tags |= {IsItem}

    for i in range(20):
        if i == 5 or i == 9:
            add_door(Position(10,i))
        else:
            add_wall(Position(10, i))

    return world


def unlock_door(door: Entity):
    door.components[Graphic] = Graphic(ord("_"))
    door.tags.clear()
    pos = door.components[Position]
    add_wall(pos, remove=True)
