#===============================================================================
# The OTBot: The Old Trailers Bot
#-------------------------------------------------------------------------------
# Version: 0.1.0
# Updated: 14-05-2014
# Author: Alex Crawford
# License: MIT
#===============================================================================

"""
A fairly simple Reddit bot, written specifically for /r/oldtrailers, that 
updates & indexes the titles of the movies/trailers posted there. 

"""

#===============================================================================
# Imports
#===============================================================================

from redbot import *

#===============================================================================
# The OTBot
#===============================================================================

class OTBot(RedBot):
    """The OTBot class, containing the attributes/methods for the bot."""

    AGENT_NAME = "Old Trailers Bot v0.1.0 by /u/Trebek604"
    VERSION = "0.1.0"

    USERNAME = ""
    PASSWORD = ""

    SUBREDDIT = "oldtrailers"

    SUB_URL = "http://www.reddit.com/r/oldtrailers/"

    FLAIR = ["Trailer", "Teaser", "TV Spot", "VHS Trailer"]
    ARTICLE_EXCEPTS = []

    MESSAGES = {
        "adding": "New titles found. Adding titles to local data...\n",
        "buildpage_alpha": "Building alphabetical movies wiki page...\n",
        "buildpage_year": "Building decade separated movies wiki pages...\n",
        "edit_wiki": "Editing/updating wiki page: %s...\n",
        "login": "Logging in to reddit...\n",
        "getnew": "Getting %s new submissions from: /r/%s...\n",
        "getsub": "Getting subreddit: /r/%s...\n",
        "noadding": "No new titles to add.\n",
        "opendata": "Loading local movie data...\n",
        "opengz": "Opening gzipped JSON file: '%s'\n",
        "openjson": "Opening JSON file: '%s'\n",
        "savedata": "Saving local movie data...\n",
        "savegz": "Saving gzipped JSON file: '%s'\n",
        "savejson": "Saving JSON file: '%s'\n",
    }

    def __init__(self):
        """The init method for the OTBot."""

        super(OTBot, self).__init__()

        self.PATHS["movies"] = "data\\movies.gz"
        self.DATA["movies"] = None

        self.new_titles = False

    def article_fix(self, title):
        """
        Checks for an article before a given title, and if found, moves it to
        the end of the title, and returns the modified title. 

        """
        form_str = "%s, %s %s"

        if title not in self.ARTICLE_EXCEPTS:
            if title[:2] == "A ":
                return form_str % (title[2:][:-7], title[:1], title[2:][-6:])
            elif title[:3] == "An ":
                return form_str % (title[3:][:-7], title[:2], title[3:][-6:])
            elif title[:4] == "The ":
                return form_str % (title[4:][:-7], title[:3], title[4:][-6:])
        
        return title

    def build_page_alpha(self):
        """
        Builds the movies wiki page, containing an alphabetical listing
        of titles posted to the subreddit.

        """
        self.print_and_log(self.MESSAGES["buildpage_alpha"])

        hr = "\n--------\n"

        date = self.get_date()

        alpha_titles = self.sort_by_alpha(self.DATA["movies"])

        header = "# Movies"
        footer = (
            "--------\n\n"
            "*This page was generated automatically by "
            "the OTBot (%s).*\n" % (date)
        )

        page = [header, hr, "\n"]

        for letter in sorted(alpha_titles):
            page.append("## %s%s" % (letter, hr))
            for title in alpha_titles[letter]:
                md_link = "[%s](%s)  \n" % (
                    self.article_fix(title), 
                    self.DATA["movies"][title]["search"]
                )
                page.append(md_link)
            page.append("\n")

        page.append(footer)

        return page

    def build_page_decade(self):
        """
        Builds the movies wiki page, containing an alphabetical listing
        of titles posted to the subreddit.

        """
        self.print_and_log(self.MESSAGES["buildpage_year"])

        hr = "\n--------\n"

        date = self.get_date()

        titles_decade = self.sort_by_decade(self.DATA["movies"])

        pages = {
            "1930s": [], "1940s": [], "1950s": [], "1960s": [], "1970s": [],
            "1980s": [], "1990s": []
        }

        footer = (
            "--------\n\n"
            "*This page was generated automatically by "
            "the OTBot (%s).*\n" % (date)
        )

        sorted_decades = sorted(titles_decade)

        for decade in sorted_decades:
            sorted_years = sorted(titles_decade[decade])
            header = "# Movies (%s)" % (decade)
            pages[decade].extend([header, hr, "\n"])
            for year in sorted_years:
                subheader = "## %s" % (year)
                pages[decade].extend([subheader, hr])
                for title in titles_decade[decade][year]:
                    md_link = "[%s](%s)  \n" % (
                        self.article_fix(title), 
                        self.DATA["movies"][title]["search"]
                    )
                    pages[decade].append(md_link)