"""
File: server.py
Author: Mark Grivainis
Email: mark.grivainis@fenyolab.org
Github: https://github.com/MarkGrivainis
Description: Local server for files generated by TranspoScope.
             Due to the TranspoScope web page using ajax requests a web server
             is required.
"""
import json
import os
import webbrowser
from functools import reduce

import cherrypy

# TODO: do a search of the JSON folder and make a home page with links to all
#       options
class App:
    pass


def build_tree(path):
    dir = {}
    rootdir = path.rstrip(os.sep)
    found_table_info = False
    start = rootdir.rfind(os.sep) + 1
    for path, dirs, files in os.walk(rootdir):
        folders = path[start:].split(os.sep)
        subdir = dict()
        if "table_info.json.gz.txt" in files:
            found_table_info = True
        parent = reduce(dict.get, folders[:-1], dir)
        parent[folders[-1]] = subdir
    return dir, found_table_info


def main(args=None):
    PATH = os.path.abspath(args.web_directory)
    CONTENT_PATH = os.path.join(PATH, "json")
    config = {
        "/": {
            "tools.staticdir.on": True,
            "tools.staticdir.dir": PATH,
            "tools.staticdir.index": "home.html",
        }
    }
    tree, found_table = build_tree(CONTENT_PATH)
    if not found_table:
        print(
            "ERROR: table_info.json.gz.txt was not found in the specified "
            "directory"
        )
    else:
        with open(os.path.join(PATH, "manifest.json"), "w") as json_file:
            json.dump(tree["json"], json_file)

        cherrypy.tree.mount(App(), "/", config)

        cherrypy.engine.start_with_callback(
            webbrowser.open, ("http://localhost:8080/",)
        )
        cherrypy.engine.block()


if __name__ == "__main__":
    main()
