#!/usr/bin/env python

from os.path import exists
from datetime import datetime
from random import randint
from re import split, match
from shutil import copyfile

from evennia import CmdSet
from evennia.utils import logger, delay

from commands.command import Command
from typeclasses.objects import Object, Listener
from typeclasses.characters import Character
from utils.word_list import routput


class StoryCube(Object, Listener):
    """
    An invisible puppet to respond to situations.

    @create/drop cube1:typeclasses.puppets.StoryCube
    @desc cube1 = Description for Admins
    @lock cube1 = view:false()  # to make it invisible
    """


class Changling(StoryCube):
    """
    Object that changes appearance every time someone looks at it.

    Important Attribute:
      desc_prefix (string): The initial part of the description.
          This can be an empty string.

      desc_postfix (string): The final part of the description.
          This can be an empty string.

      descs (list): list of descriptions. One of these is
          picked randomly when this object is looked at and its index
          in the list is used as a key for to solve the puzzle.
    """

    def at_object_creation(self):
        """Called when object is created."""
        super().at_object_creation()
        self.db.desc_prefix = ""
        self.db.desc_postfix = ""
        self.db.descs = ["You don't see anything particular."]

    def return_appearance(self, caller):
        """
        This hook is called by the look command to get the description
        of the object. We overload it with our own version.
        """
        def optional(text, prefix=False):
            if text and text != "":
                return ("" if prefix else " ") + \
                    routput(text) + \
                    (" " if prefix else "")
            else:
                return ""

        # Randomly get the index for one of the descriptions:
        descs = self.db.descs
        clueindex = randint(0, len(descs) - 1)

        # Remember the last view as it could be a clue for later:
        key_id = self.key.lower().replace(" ", "_") + "_view_index"

        if self.attributes.get("desc_first_prefix") and \
           not caller.nattributes.get(key_id):
            prefix = optional(self.db.desc_first_prefix, True)
        else:
            prefix = optional(self.db.desc_prefix, True)

        # set this description, with the random extra
        self.db.desc = prefix + descs[clueindex] + optional(self.db.desc_postfix)

        caller.nattributes.add(key=key_id, value=clueindex)
        # call the parent function as normal (this will use
        # the new desc Attribute we just set)
        # return super().return_appearance(caller)
        return self.db.desc

    def at_object_receive(self, obj, giver, **kwargs):
        """
        Workaround for a particular puzzle. Perhaps we can get rid of this.
        """
        if obj.key == 'conch':
            return super().at_object_receive(obj, giver)

        obj.move_to(self.location, quiet=True, move_type="drop")
        delay(2, giver.announce_action,
              f"Soon after $you() $conj(place) a {obj.name} in the open cavity of the obelisk, it falls to the floor.")
        return True


class Stateful(Object):
    """
    Each character can have a different view of this object.

    @set person/duck_state_value = "pink"

    @set duck/name_pink = "pink duck"
    @set duck/desc_pink = "This is a pink duck."
    @set duck/name_blue = "blue duck"
    @set duck/desc_blue = "This is a blue duck."
    @set duck/initial_state = "blue"
    """
    def return_appearance(self, looker, **kwargs):
        state = looker.attributes.get(f"{self.key}_state_value") \
            or self.db.initial_state or "default"
        desc = self.attributes.get(f"desc_{state}")
        if desc:
            return desc
        return super().return_appearance(looker, **kwargs)

    def get_display_name(self, looker, **kwargs):
        state = looker.attributes.get(f"{self.key}_state_value") \
            or self.db.initial_state or "default"
        name = self.attributes.get(f"name_{state}")
        if name:
            return name
        return super().get_display_name(looker, **kwargs)
