"""Various functions that can generate various things for the bot"""
import discord
import config
import math
from modules import tvmaze, strings

help_embed_fields = {
    "tv_show_information":
        {"title": "TV Show Information",
         "body": "`tv!info [show]` - gets general information on the specified show\n"
         "`tv!hiatus [show]` - determines the hiatus of the specified show\n"
         "`tv!nextpremiere [show]` - determines how long it will be until the next episode of a show airs on TV\n"
         "`tv!cast [show]` - gets cast information for the specified show\n"
         "`tv!crew [show]` - gets crew information for the specified show\n"
         "`tv!character [name], [show]` - gets information on the specified character for the specified show\n"
         "`tv!akas [show]` - displays names of the specified show in other languages\n"
         "`tv!poster [show]` - displays the specified show's poster"},
    "episode_information":
        {"title": "Episode Information",
         "body": "`tv!episodeinfo [episode-name], [show]` or "
                 "`tv!episodeinfo [season-number], [episode-number], [show]` - "
                 "displays information for the specified episode of the specified show, "
                 "searching *either* by episode name *or* by season and number\n"
                 "`tv!episodelist <optional:season>, [show]` - if a season is provided, "
                 "list all episodes of that season. Otherwise, list all episodes of that show\n"
                 "`tv!lastepisodeinfo [show]` - displays information about "
                 "the most recent episode of the specified show\n"
                 "`tv!nextepisodeinfo [show]` - displays information about "
                 "the episode that will air next of the specified show"},
    "people_information":
        {"title": "People Information",
         "body": "`tv!people [person]` - gets general information on the specified person\n"
                 "`tv!castcredits [person]` - displays all the shows and role names "
                 "that the specified person has served as a cast member for\n"
                 "`tv!crewcredits [person]` - displays all the shows "
                 "that the specified person has served as a crew member for and their position"},
    "fun_and_games":
        {"title": "Fun and Games",
         "body": "`tv!guesstheepisode [show]` - if the specified show is available to the host of this bot, "
                 "play a fun episode guessing game\n"
                 "`tv!availableshows` - lists TV shows available for use with guess the episode\n"
                 "`tv!gamestatus` - Checks to see if a game session of Guess the Episode is being prepared "
                 "for the channel the command is run in, or gives information about the active game session\n"
                 "`tv!makegif [show]` - Allows you to create a GIF from your favorite TV show, "
                 "just follow the instructions given by the bot\n"
                 "`tv!makemp4 [show]` - Allows you to create a MP4 video from your favorite TV show, "
                 "just follow the instructions given by the bot"},
    "voice_commands":
        {"title": "Voice Commands",
         "body": "`tv!playtheme [show]` - plays the theme song for the specified TV show "
                 "in the voice channel the user is in\n"
                 "`tv!playepisode [episode-name], [show]` or "
                 "`tv!playepisode [season-number], [episode-number], [show]` - "
                 "if the specified episode is available for TVBot, "
                 "plays the audio from the specified episode in the voice channel the user is in\n"
                 "`tv!nowplaying` - shows what the TVBot player is currently playing\n"
                 "`tv!queue` - shows the audio queue for the TVBot player\n"
                 "`tv!skip` - skips the TVBot player to the next entry in the queue\n"
                 "`tv!move` - moves TVBot to the voice channel of the user that ran the command\n"
                 "`tv!pause` - pauses the audio player\n"
                 "`tv!resume` - resumes the audio player\n"
                 "`tv!leave` - leaves the voice channel"},
    "commands_for_server_admins":
        {"title": "Commands for Server Admins",
         "body": "`tv!addepisodenotification [show]` - adds a notification for whenever the specified show premieres "
                 "a new episode for the channel in which the command is run\n"
                 "`tv!configurenotifications` - allows you to add custom text to or remove a registered notification\n"
                 "`tv!setserverdefault [show]` - specifies which show to provide information on if "
                 "no query is specified by the user, *useful for communities centered around a TV show*\n"
                 "`tv!removeserverdefault` - removes the default TV show from the server"},
    "misc_commands":
        {"title": "Misc. Commands",
         "body": "`tv!episodenotifications` - lists all new episode notifications "
                 "registered to the channel in which the command is ran\n"
                 "`tv!defaultshow` - displays the default TV show for the current server\n"
                 "`tv!help` - view the help for TVBot"},
    "command_syntax":
        {"title": "Command Syntax",
         "body": "Commands are formatted like this: `tv!command [argument]`. "
                 "Some commands have more than one argument, in which case aguments are separated by a comma. "
                 "You *do not* type the brackets around the command argument.\n"
                 "**Examples:**\n"
                 "1. `tv!hiatus The Flash`\n"
                 "2. `tv!cast Westworld`\n"
                 "3. `tv!playepisode S1, E2, Caprica`\n"
                 "4. `tv!episodeinfo Let's Be Friends, OK K.O.! Let's Be Heroes`"}
}


def generate_episode_information_embed(show_data, episode_data, embed_title, add_timezone=False, add_network=False):
    airtime_string = ""
    if not episode_data["airtime"] == "":
        airtime_string = " at " + episode_data["airtime"]

    episode_info_embed = discord.Embed(title=embed_title, color=config.embed_color)
    if show_data["image"] is not None and not show_data["image"]["original"] == "":
        episode_info_embed.set_thumbnail(url=show_data["image"]["original"])
    if episode_data["image"] is not None and not episode_data["image"]["original"] == "":
        episode_info_embed.set_image(url=episode_data["image"]["original"])
    episode_info_embed.add_field(name="Episode Name:", value=episode_data["name"])
    episode_info_embed.add_field(name="Season and Episode Number:", value="Season " + str(episode_data["season"]) + ", Episode " + str(episode_data["number"]))
    episode_info_embed.add_field(name="Episode Runtime:", value=str(episode_data["runtime"]) + " minutes")
    episode_info_embed.add_field(name="Air Date:", value=episode_data["airdate"] + airtime_string)
    if add_timezone:
        episode_info_embed.add_field(name="Timezone of Initial Airing:", value=tvmaze.TVMaze.determine_country_information(show_data, "timezone"))
    if add_network:
        episode_info_embed.add_field(name="Network", value=tvmaze.TVMaze.determine_network_name(show_data))
    if not episode_data["summary"] == "" and episode_data["summary"] is not None:
        episode_info_embed.add_field(name="Summary:", value=strings.remove_html_tags(episode_data["summary"]))

    return episode_info_embed


def add_list_embed_fields(output_string, embed, header, cutoff_mode=False):
    if len(output_string) <= 1024:
        embed.add_field(name=header, value=output_string)
    else:
        sections = []
        num_sections = math.ceil(len(output_string) / 1024)
        index_of_first_newline = 0
        index_of_last_newline = 0
        for i in range(0, num_sections):
            n = index_of_first_newline
            for c in output_string[index_of_first_newline:index_of_first_newline + 1024]:
                if c == '\n' or cutoff_mode:
                    index_of_last_newline = n
                n += 1
            sections.append(output_string[index_of_first_newline:index_of_last_newline + 1])
            index_of_first_newline = index_of_last_newline
        continued_string = ""
        for section in sections:
            embed.add_field(name=header + continued_string, value=section)
            continued_string = " (Continued)"


def generate_base_help_embed():
    help_embed = discord.Embed(title="TVBot Help", color=config.embed_color)
    help_embed.set_thumbnail(
        url="https://lh3.googleusercontent.com/4_6RCvNJCXXObqH9ao9mcJH7LfTTFRG3Yx4-ETJdEX8zuuUuSyxd_ytYUpZiqYWS_GU=w170")
    help_embed.set_footer(text="Developed by ktraw2#9962")
    return help_embed


def add_help_embed_field(help_embed, key):
    help_embed.add_field(name=help_embed_fields[key]["title"], value=help_embed_fields[key]["body"])


def add_help_embed_footer_links(help_embed):
    help_embed.add_field(name=":globe_with_meridians: TVBot Website",
                         value="Visit TVBot on the World Wide Web at https://ktraw2.github.io/TVBot")
    help_embed.add_field(name="<:discord:391484243403997184> TVBot Discord",
                         value="Join the official TVBot Discord at https://discord.gg/jgXx9Cw "
                               "for information, support, or just to have a chat!")
    help_embed.add_field(name="<:transparenttvbot:347931264705101824> Bring TVBot to Your Discord",
                         value="[Click here](https://discordapp.com/oauth2/authorize?client_id="
                               "342440109859143682&scope=bot&permissions=0) "
                               "to invite TVBot to your own Discord server")
    help_embed.add_field(name=":arrow_up: Support TVBot",
                         value="Support TVBot by upvoting it "
                               "[here](https://discordbots.org/bot/342440109859143682)!")