#!/usr/bin/python

from bs4 import BeautifulSoup
import json, urllib, re, os, sys
from pprint import pprint

def main():
    root = "../games-for-launcher"
    soup = BeautifulSoup(open("games.html"), "html.parser")
    config = {
        "presetList":
        [
            {
                "presetName": "Action",
                "gameList": ["TurtlesInTime", "Contra"]
            }
        ],
        "gameList": []
    }
    for row in soup.find_all("tr"):
        header = row.find("div", class_="row-header-wrapper")
        if header and int(header.string) >= 4:
            cells = row.find_all("td")
            category = cells[6].string
            if category and category.strip() == "digital":
                game = {}
                game["gameName"] = cells[0].string.encode("utf-8")
                game["gameAuthor"] = [cells[2].string.encode("utf-8")]
                directory = ""
                for c in game["gameName"]:
                    if c.isalnum():
                        directory += c
                    else:
                        directory += "_"
                game["gameId"] = directory
                game["executablePath"] = os.path.join(directory, directory + ".exe")
                if "--make-directories" in sys.argv:
                    os.mkdir(os.path.join(root, directory), 0755)
                text = cells[5].get_text(strip=True)
                if text:
                    game["gameDescription"] = text.encode("utf-8")
                else:
                    game["gameDescription"] = ""
                url = cells[1].get_text(strip=True)
                game["screenshotName"] = os.path.join(directory, "ss.png")
                if url.startswith("http"):
                    tw = BeautifulSoup(urllib.urlopen(url), "html.parser")
                    img_container = tw.find("div", class_="field-field-screenshot")
                    if img_container and "--download-screenshots" in sys.argv:
                        ss_url = img_container.find("img")["src"]
                        urllib.urlretrieve(ss_url, os.path.join(root, directory, "ss.png"))
                    for tag in tw.find_all("div", class_="field-label"):
                        if tag.get_text(strip=True) == "Game File:":
                            href = tag.parent.find("a")["href"]
                            if "--download-games" in sys.argv:
                                urllib.urlretrieve(href, os.path.join(root, directory, os.path.basename(href)))
                            break
                config["gameList"].append(game)
    fp = open(os.path.join(root, "launcherConfig.json"), "w")
    fp.write(json.dumps(config, sort_keys=True, indent=4, separators=(",", ": ")))
    fp.close()


if __name__ == "__main__":
    main()
