import datetime, os
from importlib import import_module

import headerfooter

def statslist(local=False):
    yearlist = []
    ficcount = 500
    while ficcount > 0:
        ficcount -= 1
        if ficcount < 10:
            ficcountstring = "00" + str(ficcount)
        elif ficcount < 100:
            ficcountstring = "0" + str(ficcount)
        else:
            ficcountstring = str(ficcount)
        if os.path.exists("files/originalsmeta/" + ficcountstring + ".py"):
            ficfile = "files.originalsmeta." + ficcountstring
            fileread = import_module(ficfile)
        elif os.path.exists("files/translationsmeta/" + ficcountstring + ".py"):
            ficfile = "files.translationsmeta." + ficcountstring
            fileread = import_module(ficfile)
        else:
            fileread = False
        if fileread:
            try:
                if fileread.revealdate > datetime.datetime.now():
                    revealed = False
                else:
                    revealed = True
            except:
                revealed = True
            if revealed == True:
                for date in fileread.datewords:
                    yearlist.append(date["date"].year)
                    yearlist = sorted(list(dict.fromkeys(yearlist)))
    linkedyears = []
    for year in yearlist:
        statstring = ""
        if local == True:
            statspath = "/home/mdd/Documents/proj/fic-archive/build/stats/" + str(year) + "/index.html"
        else:
            statspath = "/fic/stats/" + str(year)
        if yearlist.index(year) > 0:
            statstring += "&nbsp;• "
        statstring += "<a href=\"" + statspath + "\">" + str(year)
        if year == (datetime.datetime.now()).year:
            statstring += " (so far)"
        statstring += "</a>"
        linkedyears.append(statstring)
    listofyears = "".join(linkedyears)
    return listofyears

def indexgen(local=False):
    # delete existing file
    if os.path.exists("build/index.html"):
        os.remove("build/index.html")
    # write header
    headerfooter.headerwrite("build/index.html","Tré’s fic archive","Tré’s fic archive","",True,local)
    filewrite = open("build/index.html", "a")
    filewrite.write("<p>Here is all my fanfiction! Some of it is also syndicated elsewhere, but this site is the canonical location for everything I’ve written.</p>\n<p xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:dct=\"http://purl.org/dc/terms/\"><strong>Transformative works policy:</strong> The contents of <a property=\"dct:title\" rel=\"cc:attributionURL\" href=\"https://tre.praze.net/fic\">these pages</a> are licensed under <a href=\"https://creativecommons.org/licenses/by-nc/4.0/\" target=\"_blank\" rel=\"license\" style=\"display:inline-block;\">CC BY-NC 4.0. <img style=\"height:22px!important;margin-left:3px;vertical-align:middle;\" src=\"https://mirrors.creativecommons.org/presskit/icons/cc.svg?ref=chooser-v1\" alt=\"\"><img style=\"height:22px!important;margin-left:3px;vertical-align:middle;\" src=\"https://mirrors.creativecommons.org/presskit/icons/by.svg?ref=chooser-v1\" alt=\"\"><img style=\"height:22px!important;margin-left:3px;vertical-align:middle;\" src=\"https://mirrors.creativecommons.org/presskit/icons/nc.svg?ref=chooser-v1\" alt=\"\"></a> In other words, transformative works are permitted as long as there is a clearly visible hyperlink to the original and no financial transactions are involved.</p>\n<p>The code for this archive is available <a href=\"https://git.praze.net/tre/fic-archive\">here</a>. Commenting is switched on for most fics written at least semi-recently – read about that <a href=\"")
    if local:
        filewrite.write("comments/index.html")
    else:
        filewrite.write("/fic/comments")
    filewrite.write("\">here</a>.</p>\n<p>You can also subscribe to <a href=\"")
    if not local:
        filewrite.write("/fic/")
    filewrite.write("feed.xml\">the RSS feed</a> to be notified of new fics and updates to existing ones.</p>\n<div class=\"fic\">\n<h2>Masterlist</h2>\n<p>Every fic I’ve written since the age of five. You can view these:\n<ul>\n<li><a href=\"")
    if local:
        filewrite.write("masterlist/index.html")
    else:
        filewrite.write("/fic/masterlist")
    filewrite.write("\">chronologically</a></li>\n<li><a href=\"")
    if local:
        filewrite.write("byfandom/index.html")
    else:
        filewrite.write("/fic/byfandom")
    filewrite.write("\">by fandom</a></li>\n</ul>\n</div>\n<div class=\"fic\">\n<h2>Final Fantasy</h2>\n<p>Most of the fics I write are in FF fandoms these days. You can browse them:</p>\n<ul>\n<li><a href=\"")
    if local:
        filewrite.write("ff/characters/index.html")
    else:
        filewrite.write("/fic/ff/characters")
    filewrite.write("\">by character</a></li>\n<li><a href=\"")
    if local:
        filewrite.write("ff/ships/index.html")
    else:
        filewrite.write("/fic/ff/ships")
    filewrite.write("\">by ship</a></li>\n<li><a href=\"")
    if local:
        filewrite.write("ff/bywords/index.html")
    else:
        filewrite.write("/fic/ff/bywords")
    filewrite.write("\">by length</a></li>\n</ul>\n</div>\n<div class=\"fic\">\n<h2><a href=\"")
    if local:
        filewrite.write("events/index.html")
    else:
        filewrite.write("/fic/events")
    filewrite.write("\">Events</a></h2>\n<p>Since 2020 I’ve participated in some fandom exchanges and other events. Many of my more recent fics are in this category.</p>\n</div>\n<div class=\"fic\">\n<h2>Other</h2>\n<ul>\n<li>Stats by year: " + (str(statslist(local))) + "</li>\n</ul>\n</div>\n<div align=\"center\">\n<script>\ndocument.write('<script src=\"https://ficring.neocities.org/ring.js\"><\/script>');\n</script>\n</div>\n")
    filewrite.close()
    headerfooter.footerwrite("build/index.html",True,local)

if __name__ == "__main__":
    statslist(True)
    indexgen(True)