"""
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 threading
import time
import webbrowser
from functools import reduce, partial

# import cherrypy
import http.server
import socketserver


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" in files:
            found_table_info = True
        parent = reduce(dict.get, folders[:-1], dir)
        parent[folders[-1]] = subdir
    return dir, found_table_info


PORT = 8080


# def run_handler(path):


def main(args=None):
    PATH = os.path.abspath(args.web_directory)
    CONTENT_PATH = os.path.join(PATH, "data")
    tree, found_table = build_tree(CONTENT_PATH)
    if not found_table:
        print("ERROR: table_info.json was not found in the specified " "directory")
    else:
        with open(os.path.join(PATH, "data/manifest.json"), "w") as json_file:
            print("Checking Data folders")
            json.dump(tree["data"], json_file)

    Handler = partial(http.server.SimpleHTTPRequestHandler, directory=PATH)
    socketserver.TCPServer.allow_reuse_address = True
    with socketserver.TCPServer(("", PORT), Handler) as httpd:
        print("serving at http://0.0.0.0:{}".format(PORT))
        print("Press Ctrl + C to stop serving")
        webbrowser.open("http://0.0.0.0:{}".format(PORT))
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            httpd.shutdown()
            httpd.server_close()
            print("\nGoodbye")

    # while True:
    #     time.sleep(1)


if __name__ == "__main__":
    main()
