#!/usr/bin/env python

import random
import re

from evennia import TICKER_HANDLER
from evennia.utils import delay

from typeclasses.rooms import Room

# -------------------------------------------------------------
#
# Weather room - room with a ticker
#
# -------------------------------------------------------------

# Need the time of day ...
from datetime import datetime
from pytz import timezone

TIMEBASE_WEATHER_MSGS = [
    # Night
    [   # Clear
        "The clouds part and you can see stars glitter against the black velvet night.",
        "You hear distant howls as the moon appears.",
        # Cloudy
        "The clouds gather making the night dark and hard to see.",
        "The rain slows while ghostly mists weave through the trees.",
        # Rainy
        "The rain coming down from the inky, black sky intensifies.",
        "For a moment it looks like the rain is slowing, then it begins anew with renewed force.",
        "The rain pummels you with large, heavy drops. You hear the rumble of thunder in the distance.",
        "Bright fingers of lightning flash over the sky, moments later followed by a deafening rumble.",
        "It rains so hard you can hardly see your hand in front of you. You'll soon be drenched.",
        "Lightning strikes in thundering bolts.",
        # Windy
        "A gust of wind throws the rain right in your face. Despite your cloak you shiver.",
        "The wind is picking up, howling around you, throwing water droplets in your face. It's cold.",
    ],
    # Morning
    [   # Clear
        "The clouds part creating a dazzling sunrise of colors.",
        "Bird song fills the air with the dawn chorus.",
        # Cloudy
        "The clouds accumulate making the morning last longer.",
        "The rain slows to a drizzle as the moss begins to glow in the brightening light.",
        # Rainy
        "The falling rain intensifies creating vibrating puddles.",
        "The morning breeze smells sweet.",
        # Windy
        "The wind is picking up. Today may be a good day for a kite.",
    ],
    # Noon
    [
        "The clouds part and the sun illuminates the scene. The morning's rain evaporates, warming the air.",
    ],
    # Afternoon
    [
        "A lazy afternoon filled with the sound of bees and other insects.",
        "A gentle breeze wafts the scent of distant flowers.",
        "A low breeze fills the air with the earthy scent of mushrooms.",
    ],
    # Evening
    [
        # Clear
        "The clouds part creating a dazzling sunset of colors.",
        "Bird song fills the air with the evening chorus.",
        # Cloudy
        "The clouds accumulate. Night is approaching.",
        "The rain slows while ghostly mist weave through the darkening gloom.",
        # Rainy
        "The falling rain intensifies making the evening somber.",
        "For a moment it looks like the rain is slowing, then it begins anew with renewed force.",
        "The rain pummels you with large, heavy drops. You hear the rumble of thunder in the distance.",
        # Windy
        "A gust of wind throws the rain right in your face. Despite your cloak you shiver.",
        "The wind is picking up, howling around you in the darkening evening.",
    ],
]


def watches(now=None):
    """
    Would be nice to get the sunrise/sunset of my area.
    But Python's datetime, timezone and libraries are awful.
    """
    tz_name = 'America/Los_Angeles'
    local_tz = timezone(tz_name)
    if not now:
        now = datetime.now(local_tz)

    if now.hour < 4 or now.hour > 22:
        return 0  # Night
    if now.hour < 10:
        return 1  # Morning
    if now.hour < 13:
        return 2  # Noon
    if now.hour < 18:
        return 3  # Afternoon
    return 4      # Evening


def choose_weather_message():
    return random.choice(TIMEBASE_WEATHER_MSGS[watches()])


class TimeWeatherRoom(Room):
    """
    This sets up an outdoor room typeclass. At irregular intervals,
    the effects of weather will show in the room based on the time of day.
    Outdoor rooms should inherit from this.

    """

    def at_object_creation(self):
        """
        Called when object is first created.
        We set up a ticker to update this room regularly.

        Note that we could in principle also use a Script to manage
        the ticking of the room; the TickerHandler works fine for
        simple things like this though.
        """
        super().at_object_creation()
        # subscribe ourselves to a ticker to repeatedly call the hook
        # "update_weather" on this object. The interval is randomized
        # so as to not have all weather rooms update at the same time.
        self.db.interval = random.randint(50, 70)
        TICKER_HANDLER.add(
            interval=self.db.interval, callback=self.update_weather
        )

    def update_weather(self, *args, **kwargs):
        """
        Called by the tickerhandler at regular intervals. Even so, we
        only update 20% of the time, picking a random weather message
        when we do. The tickerhandler requires that this hook accepts
        any arguments and keyword arguments (hence the *args, **kwargs
        even though we don't actually use them in this example)
        """
        # only update 10 % of the time
        if random.random() < 0.06:
            msg = choose_weather_message()
            if self.db.previous_weather != msg:
                self.db.previous_weather = msg
                self.msg_contents(f"|w{msg}|n\n")

from commands.pets import (CmdSetKiss)

class FrogMeadow(TimeWeatherRoom):
    """
    Add the 'kiss' command in this room only.
    """
    def at_object_creation(self):
        self.cmdset.add(CmdSetKiss, persistent=True)

    def kiss_response(self, kisser, kissed):
        if re.match(r".*frog.*", kissed):
            kisser.announce_action("$You() $conj(catch) a cute little frog, and $conj(give) it a kiss.")
            delay(2, kisser.transmogrify, "frog",
                  "Cute frog with big black eyes and a tiny gold crown.")
            delay(60, kisser.untransmogrify)
            delay(62, kisser.msg, "Whew. Glad that effect didn't last that long.")
        else:
            kisser.msg("Uh, really? You want to kiss that?")
