import logging
from examples.voroni_world.models import *
from coopgame.gameTemplate import tt
from cooptools.decor import timer
import pprint
import math
from typing import Dict, Tuple, List, Callable
from cooptools import graphs as grph
from cooptools.physics import waypointFollower as wf
from examples.voroni_world.behaviors import cmn

logger = logging.getLogger(__name__)


FARM_ACTION = "FARMING"

def _choose_farmable_region(regions: Dict[int, Region]):
    try:
        to_farm = next(v for v in regions.values()
                    if v.terrain in [TerrainType.GRASS, TerrainType.GRASSHILLS]
                    and v.visibility_level in [VisibilityLevel.REVEALED]
                    and FARM_ACTION not in v.action_states)
    except:
        to_farm = None

    return to_farm


def farm(
        villager: Villager,
        villager_current_region_provider: Callable[[Villager], Region],
        route_provider: Callable[[Region, Region], grph.AStarResults],
        route_to_waypoints_provider: Callable[[List[grph.Node]], List[wf.Waypoint]],
        village_region: Region,
        regions: Dict[int, Region],
):

    to_farm = _choose_farmable_region(
        regions=regions
    )

    if to_farm is None:
        logger.error(f"No farm-able region")
        return

    cmn.send_villager_to_region(
        villager=villager,
        region=to_farm,
        villager_current_region_provider=villager_current_region_provider,
        route_provider=route_provider,
        route_to_waypoints_provider=route_to_waypoints_provider,
    )

