import discogs_client,re,time,variables
d = discogs_client.Client("Python/1.0",user_token=variables.discogstoken)

user = d.user(variables.discogsuser)

try:
    if sys.argv[1] == "local":
        local = True
    else:
        local = False
except:
    local = False

if variables.trackrecords == True:

    records = []

    thenumber = 1
    maxno = len(user.collection_folders[0].releases)

    def typography(thestring):
        return re.sub(" / ","/",re.sub(" \(.*\)","",re.sub(" - "," – ",re.sub("  "," ",re.sub("\.\.\."," …",re.sub("'","’",re.sub(" = .*","",thestring)))))))

    print("Fetching records from Discogs")

    for item in user.collection_folders[0].releases:
        print("Fetching " + str(thenumber) + " of " + str(maxno))
        theitem = {}
        theitem["artist"] = typography(item.release.artists[0].name)
        theitem["title"] = typography(item.release.title)
        try:
            if "LP" in item.release.formats[0]["descriptions"] or "12\"" in item.release.formats[0]["descriptions"]:
                theitem["format"] = "large"
            else:
                theitem["format"] = "small"
        except:
            theitem["format"] = "small"
        try:
            theitem["img"] = item.release.images[0]["uri"]
        except:
            pass
        records.append(theitem)
        thenumber += 1
        time.sleep(1) # only allowed 1 request per second

    records = sorted(records, key=lambda d: d["title"])
    records = sorted(records, key=lambda d: d["artist"])

    smalls = []
    larges = []
    for record in records:
        if record["format"] == "large":
            larges.append(record)
        else:
            smalls.append(record)

    def recordwrite(record):
        recordstring = "      <div class=\"container " + record["format"] + "\">\n        <img src=\""
        try:
            recordstring += record["img"]
        except:
            if record["format"] == "large":
                if local:
                    recordstring += variables.domain
                recordstring += variables.recordserverpath + "large.png"
            elif record["format"] == "small":
                if local:
                    recordstring += variables.domain
                recordstring += variables.recordserverpath + "small.png"
        recordstring += "\">\n        <div>\n          <p>" + record["artist"] + "<br>•<br>" + record["title"] + "</p>\n        </div>\n      </div>\n"
        return recordstring

    writefile = open("recordbuild/index.html","w")

    writefile.write("<!DOCTYPE html>\n<html>\n  <head>\n    <link rel=\"stylesheet\" href=\"")
    if local:
        writefile.write(variables.domain)
    writefile.write(variables.recordcss + "\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n    <title>Record collection</title>\n    <style>\n     main {\n       display: flex;\n       gap: 10px;\n       flex-wrap: wrap;\n       justify-content: space-evenly;\n     }\n     .container {\n       position: relative;\n       display: flex;\n       justify-content: center;\n     }\n     .container.small {\n       width: 180px;\n       min-width: 180px;\n     }\n     .container.large {\n       width: 300px;\n       min-width: 300px;\n     }\n     .container img {\n       display: block;\n       width: 100%;\n       height: auto;\n       margin: auto;\n     }\n     .container div {\n       position: absolute;\n       top: 0;\n       bottom: 0;\n       left: 0;\n       right: 0;\n       height: 100%;\n       width: 100%;\n       opacity: 0;\n       transition: .5s ease;\n       background-color: rgba(0,0,0,0.5);\n       overflow: auto;\n     }\n     .container:hover div {\n       opacity: 1;\n     }\n     .container div p {\n       color: white;\n       width: 100%;\n       margin: 0;\n       position: absolute;\n       top: 50%;\n       left: 50%;\n       -webkit-transform: translate(-50%, -50%);\n       -ms-transform: translate(-50%, -50%);\n       transform: translate(-50%, -50%);\n       text-align: center;\n       text-transform: lowercase;\n     }\n    </style>\n  </head>\n  <body>\n    <h1>Record collection</h1>\n    <main>\n")

    for record in smalls:
        writefile.write(recordwrite(record))

    for record in larges:
        writefile.write(recordwrite(record))

    writefile.write("    </main>\n  <p>Generic disc icons by <a href=\"https://www.flaticon.com/free-icon/cd_5344201\">popo2021</a> and <a href=\"https://www.flaticon.com/free-icon/disc_5613845\">Dinosoft Labs</a> on Flaticon.<p>\n  </body>\n</html>\n")

    writefile.close()