import os
import gamesort,skeleton,variables
from datetime import datetime,timedelta

"""
Generates history page and RSS feed
"""

def history(local=False):
    # delete existing files
    if not os.path.isdir("build/history"):
        os.mkdir("build/history")
    if os.path.exists("build/history/index.html"):
        os.remove("build/history/index.html")
    if os.path.exists("build/feed.xml"):
        os.remove("build/feed.xml")
    # write header
    skeleton.headerwrite("build/history/index.html","history",local)
    output = "build/history/index.html"
    filewrite = open(output, "a")

    filewrite.write("            <section class=\"history\">\n              <div class=\"list\">\n")

    feedwrite = open("build/feed.xml", "a")
    feedwrite.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<rss version=\"2.0\" xmlns:atom=\"http://www.w3.org/2005/Atom\">\n  <channel>\n    <atom:link href=\"" + variables.domain + variables.serverpath + "feed.xml\" rel=\"self\" type=\"application/rss+xml\" />\n    <title>Static backlog</title>\n    <link>" + variables.domain + variables.serverpath + "backlog</link>\n    <description>Feed for gaming updates</description>\n    <language>en-gb</language>")

    theyear = int(gamesort.thisyear)
    while theyear >= variables.startyear:
        yearlist = []
        enddate = datetime.strptime((str(theyear) + "-12-31"),"%Y-%m-%d")
        startdate = datetime.strptime((str(theyear) + "-01-01"),"%Y-%m-%d")
        eachdate = enddate
        while eachdate >= startdate:
            for game in gamesort.games:
                if game["initialdate"] == eachdate:
                    yearlist.append({"date":eachdate,"name":game["name"],"console":game["console"],"action":"Added"})
                try:
                    if game["firstplayed"] == eachdate:
                        yearlist.append({"date":eachdate,"name":game["name"],"console":game["console"],"action":"Started"})
                except:
                    pass
                try:
                    if game["beaten"] == eachdate:
                        yearlist.append({"date":eachdate,"name":game["name"],"console":game["console"],"action":"Beat"})
                except:
                    pass
                try:
                    if game["completed"] == eachdate:
                        yearlist.append({"date":eachdate,"name":game["name"],"console":game["console"],"action":"Completed"})
                except:
                    pass
            eachdate -= timedelta(days=1)
        checkdate = enddate
        for event in yearlist:
            filewrite.write("                <div>\n")
            if checkdate != event["date"]:
                filewrite.write("                  <h2>" + event["date"].strftime("%Y-%m-%d") + "</h2>\n")
            filewrite.write("                  <div>\n                    <div> " + event["action"] + "\n                      <div class=\"status-dot ")
            if event["action"] == "Started":
                fullpath = str(event["name"] + " (" + event["console"] + ")")
                if fullpath in variables.endlessgames:
                    filewrite.write("Endless")
                else:
                    filewrite.write("Started")
            else:
                filewrite.write(event["action"])
            filewrite.write("\"></div>\n                    </div>\n                    <div> " + event["name"] + "\n                      <span>(" + event["console"] + ")</span>\n                    </div>\n                  </div>\n                </div>\n")
            feedwrite.write("    <item>\n      <title>" + event["action"] + " " + event["name"] + " (" + event["console"] + ")</title>\n      <pubDate>" + event["date"].strftime("%a, %-d %b %Y") + " 00:00:00 UT</pubDate>\n      <link>" + variables.domain + variables.serverpath + "history</link>\n      <guid isPermaLink=\"false\">" + event["action"] + "-" + event["name"].replace(" ","-") + "-" + event["console"] + "</guid>\n      <description>" + event["action"] + " " + event["name"] + " (" + event["console"] + ")</description>\n    </item>\n")
            checkdate = event["date"]
        theyear -= 1

    feedwrite.write("  </channel>\n</rss>")
    feedwrite.close()

    filewrite.write("              </div>\n")

    theyear = int(gamesort.thisyear)
    filewrite.write("              <div class=\"side box_1\">\n")
    while theyear > 2016:
        yeargames = 0
        yearplaying = 0
        for game in gamesort.games:
            if game["initialdate"].year == theyear:
                try:
                    if game["gameplay"]:
                        if game["id"] not in variables.endlessgames:
                            yeargames += 1
                except:
                    yeargames += 1
        for game in gamesort.games:
            try:
                if game["beaten"].year == theyear:
                    yeargames -= 1
            except:
                try:
                    if game["completed"].year == theyear:
                        yeargames -= 1
                except:
                    pass

        yearbacklog = []
        for game in gamesort.games:
            try:
                if game["completed"].year == theyear:
                    yearbacklog.append(game)
            except:
                try:
                    if game["beaten"].year == theyear:
                        yearbacklog.append(game)
                except:
                    if game["initialdate"].year == theyear:
                        yearbacklog.append(game)

        yearcompleted = 0
        yearbeaten = 0
        yearstarted = 0
        yearadded = 0
        yeartotal = len(yearbacklog)
        if yeartotal > 0:
            for game in yearbacklog:
                try:
                    if game["initialdate"].year == theyear:
                        yearadded += 1
                except:
                    pass
                try:
                    if game["firstplayed"].year == theyear:
                        yearstarted += 1
                except:
                    pass
                try:
                    if game["completed"].year == theyear:
                        yearcompleted += 1
                except:
                    pass
                try:
                    if game["beaten"].year == theyear:
                        yearbeaten += 1
                except:
                    pass

        compare = []
        compare.append(yearadded)
        compare.append(yearstarted)
        compare.append(yearbeaten)
        compare.append(yearcompleted)
        maxvalue = max(compare)
        
        filewrite.write("                <div class=\"year-tally")
        if theyear == int(gamesort.thisyear):
            filewrite.write(" active")
        filewrite.write("\">\n                  <h2> " + str(theyear) + " Summary\n                    <span>Backlog ")
        if yeargames > 0:
            filewrite.write("▲ " + str(yeargames))
        elif yeargames == 0:
            filewrite.write(" 0")
        elif yeargames < 0:
            filewrite.write("▼ " + str(yeargames * -1))
        filewrite.write("</span></h2>\n                  <div>\n                    <div>Added</div>\n                    <div>" + str(yearadded) + "</div>\n                    <div>\n                      <div class=\"unplayed\" style=\"width: calc(95% * (" + str(yearadded) + " / " + str(maxvalue) + "));\">\n                      </div>\n                    </div>\n                  </div>\n                  <div>\n                    <div>Started</div>\n                    <div>" + str(yearstarted) + "</div>\n                    <div>\n                      <div class=\"unfinished\" style=\"width: calc(95% * (" + str(yearstarted) + " / " + str(maxvalue) + "));\">\n                      </div>\n                    </div>\n                  </div>\n                  <div>\n                    <div>Beat</div>\n                    <div>" + str(yearbeaten) + "</div>\n                    <div>\n                      <div class=\"beaten\" style=\"width: calc(95% * (" + str(yearbeaten) + " / " + str(maxvalue) + "));\">\n                      </div>\n                    </div>\n                  </div>\n                  <div>\n                    <div>Completed</div>\n                    <div>" + str(yearcompleted) + "</div>\n                    <div>\n                      <div class=\"completed\" style=\"width: calc(95% * (" + str(yearcompleted) + " / " + str(maxvalue) + "));\">\n                      </div>\n                    </div>\n                  </div>\n                </div>\n")
        theyear -= 1

    filewrite.write("              </div>\n            </section>\n")

    filewrite.close()
    skeleton.footerwrite("build/history/index.html")

if __name__ == "__main__":
    history(True)