#!/usr/bin/python

import random

from evennia import Command, CmdSet
from evennia.prototypes.spawner import spawn

from typeclasses.objects import Object
from typeclasses.rooms import DabblersRoom
from utils.word_list import routput

BOOK_EMOTIONS = [
    "sad",
    "heartfelt",
    "intense",
    "plot twisting",
    "confusing",
    "fascinating",
    "riveting",
    "humorous",
]

BOOK_TYPES = [
    "story",
    "narrative",
    "chronicle",
    "tale",
    "instructional",
    "essay collection",
]

BOOKS = {
    # Each value should begin as if it follows an "of":
    "I, Golem": "a non-carbon-based person who is also a non-conformist",
    "Do Golems Dream of Awakened Sheep?": "a golem reaches out to its creator after years of therapy reveal his anger of his existential crisis is justified",
    "The 13 Habits of Highly Effective Necromancers": "",
    "Invisible Man": "when spells become permanent",
    "Little Women": "famous female gnomes and hobbits through the centuries",
    "Are You My Mummy?": "choosing your undead servants",
    "How I Ate My Mother": "a lycanthrope confessional",
    "Zen and the Art of Punching Dragons in the Face": "a pacifist monk, who's temple is burned, seeks revenge on the dragon who had spicy tacos and indigestion",

    "The Very Hungry Carrion Crawler": "an adorable little larve who grows and grows after consuming graveyard after graveyard",
    "Pride and Phylacteries": "a group of narcissistic liches and their struggle for dominance and control of the land of lesser creatures",
    "For Whom the Die Rolls": "a fool’s guide to dice games and gambling",
    "Life and Mines of a Dwarf Prospector": "a adopted human and his attempt to blend in with her adopted dwarvish parents by starting a mining company. All works well until she delved too deep",
    "The Pied Piper": "why you shouldn’t trust bards",
    "Around the World in 80 Dimension Doors": "a contest between two wizards who, after a drunken bet, attempt to reach the Ninth Level of Hell and return",
    "Along Came a Spider": "a dungeoneer’s guide to driders and the drow",
    "The Boy Who Cried Roc": "a classic children’s tale about a boy that thought it funny to announce to the village there was a Roc nearby. One day there was, and the nobody believed him. He was the only survivor",
    "Some Like it Hot": "a guide to fire elementals",
    "Girls Gone Feywild": "a group of girls who discover a portal to the Wyldwoods, and find themselves attempting to navigate the drama of the Seelie Court of the Summer Queen. Hilarity ensues when they fail to bawk like a chicken when an Archfey utter the secret word, Pancakes",
    "50 Shades of Fey": "young elf who discovers more about herself after making a pact with an Archfey of the Unseelie Court",
    "A Handmaid’s Tail": "a collection of short stories by notable Tieflings",
    "Adventures with Muck, Berries, and Fins": "a herbalist’s guide to useful foraging",
    "Bond with the Wind": "a how to summon Air elementals",
    "Eat, Prey, Club": "a young orc and her quest for true dominance",
    "Fantastic Drinks and Where to Buy Them": "all the taverns in the land (obviously written by Nori Doublefist under the pseudonym, The Drunk Dwarf), cataloging the best and most curious drinks each tavern has to offer",
    "For Whom the Bridge Troll": "a tragic love story of a misunderstood troll who lived under a bridge",
    "Frank and his Stein": "a poor drunk named Frank",
    "Harry Otter": "a young orphan druid who lives with his boring fighter uncle and aunt who denies the existence of druids. The story sees Harry start at the Druid school led by Albus Bumbledoor, the archdruid who loves to be a Bumblebee. Bumbledoor takes Harry under his gravity defying wings and tells him the true story about how his parents died and that he is known by all druids as The Otter Who Lived. He must now meet his destiny and fight the most evil druid of all time, Voldemoth. Featuring the great cast of: Ron the Weasel, Hermione Ranger (some people can never choose only one class), Hagrid the lover of all creatures, Severus Snake and many more",
    "Harry Potter and the Sorcerer’s Kidney Stone": "how an ordinarily normal surgery gets complicated due to wild magic leaving Harry with unexpected results. Spoiler Harry gets magic and becomes Dr. Strange after prolonged contact with the Sorcerer’s insides",
    "Pride and Prestidigitation": "a coven of witches as they vie for the attention, and affection, of a traveling wizard",
    "The Ruler of the Bracelets": "two gnomes who find a bracelet of power, and they have to take it to the Burning Steppes and cast it into the Cauldron. They form the Brotherhood of the Bracelet. Along the way they’re trailed by a murloc named Gottom, who’s obsessed with the bracelet, and nine bracelet bogeymen. It could be a three-parter, called ‘Ruler of the Bracelet’. The first part would be called ‘The Brotherhood of the Bracelet’, followed by ‘A Couple of Towers’, with the climactic ending called ‘Hey, the King’s Back!’ Not bad",
    "What to Expect When You’re Spectating": "the history of the four nations written by Xanathar, a famed Beholder and crime-boss",
    "The Wyrm in the Willows": "small dragon from the countryside who learns to cook without burning the meal first",
}


class CmdLookBook(Command):
    """
    Respond with a new book to look at.
    """
    auto_help = False
    key = "look book"
    aliases = "l book"

    def func(self):
        self.obj.do_look(self.caller)


class CmdTakeBook(Command):
    """
    Generate a new book to store it with the reader.
    """
    auto_help = False
    key = "get book"
    aliases = "take book"

    def func(self):
        self.obj.do_take(self.caller)


class CmdSetRead(CmdSet):
    def at_cmdset_creation(self):
        pass  # self.add(CmdReadBook)


class CmdSetBook(CmdSet):
    def at_cmdset_creation(self):
        # self.add(CmdBurnBook)
        # self.add(CmdDropBook)
        pass


class CmdSetShelf(CmdSet):
    def at_cmdset_creation(self):
        self.add(CmdLookBook)
        self.add(CmdTakeBook)


# ----------------------------------------------------------------------

class Readable(Object):
    """
    Create with a command:

    @create/drop sign : typeclasses.readables.Readable
    @desc sign = A tall wooden post.
    @set sign/inside = "What happens when you read it."
    """
    pass


class Letter(Readable):
    """
    Something that can be read, but is _personal_, so if it is
    dropped, it is destroyed.
    """
    def at_object_creation(self):
        """
        called at creation
        """
        self.cmdset.add_default(CmdSetBook)

    def at_pre_drop(self, dropper):
        if dropper.location.key == "Dabbler's House":
            dropper.msg(f"You throw your {self.get_display_name(dropper)} into the fire and burn it.")
        else:
            dropper.msg(f"You throw your {self.get_display_name(dropper)} away.")
        self.delete()


class Book(Readable):
    def at_object_creation(self):
        """
        called at creation
        """
        self.cmdset.add_default(CmdSetBook)

    def do_read(self, reader):
        reader.announce_action("$You() $conj(read) $pron(your) book.")

    def at_pre_drop(self, reader):
        if reader.location.key == "Dabbler's House":
            reader.msg("You drop the book, but it flaps its pages, and flies back to a section on the shelf.")
            self.delete()
        else:
            return True


class Books(Object):
    book_prototype = {
        "typeclass": "typeclasses.readables.Book",
        "key": "book",
        "desc": "An old, worn, leather-bound book.",
    }

    def at_object_creation(self):
        """
        called at creation
        """
        self.cmdset.add_default(CmdSetShelf, persistent=True)

    def new_book_details(self):
        title = random.choice(list(BOOKS.keys()))
        return (
            title,
            routput("""a <<worn ^ barely read ^ pristine copy of a ^ >>
            <<leather-bound ^ vellum-bound ^ >> book, titled, |w{0}|n
            """, title),
            routput(
                """
                You <<open ^ open up ^ crack open>> your book, entitled, |w{0}|n, and read the {1} {2} of {3}.
                """,
                title,
                random.choice(BOOK_EMOTIONS),
                random.choice(BOOK_TYPES),
                BOOKS[title]
            )
        )

    def do_look(self, reader):
        (self.db.last_title, self.db.last_desc,
         self.db.last_inside) = self.new_book_details()
        reader.msg(f"You see {self.db.last_desc}.")

    def do_take(self, reader):
        if self.db.last_title:
            booktype = self.book_prototype
            booktype['desc'] = self.db.last_desc
            booktype['aliases'] = [self.db.last_title]

            book = spawn(booktype)[0]
            book.db.inside = self.db.last_inside
            book.location = reader

            reader.msg("You pick up the book.")
            self.db.last_title = None
            self.db.last_desc = None
            self.db.last_inside = None
        else:
            reader.msg("Which book do you want to take. The shelves are full of them. Perhaps you want to |glook|n at a |gbook|n?")
