from os import listdir, path

import sqlite3

import tornado.gen
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.netutil


from objects import glob

def make_app():
    """
    Make tornado application instance

    :return: Tornado Application instance
    """
    def get_files(dir):
        """
        Get all file-/directory-names in a directory with a simple blacklist

        :param str: directory to read
        :return: String[] of file/directory
        """
        return [d for d in listdir(dir) if not d.startswith("_")]

    def map_routes(dir):
        """
        Map out a directory array of modules in a given directory

        :param str: directory to map out and import
        :return: tuple( endpoint, module.handle )[] routes
        """
        routes = []
        apis = get_files(dir)
        for api in apis:
            if api.endswith(".py"):
                api = api.rstrip(".py")
                routes.append(
                    (
                        r"/%s/%s" % (dir, api), __import__("%s.%s" % (dir.replace("/", "."), api), fromlist=[""]).handler
                    ))
            else:
                routes += map_routes("%s/%s" % (dir, api))
        return routes

    routes = map_routes("api")
    return tornado.web.Application(routes)

def build_database():
	f = open("wayback.db", "w")
	f.close()

	glob.sql = glob.new_sql()
	cur = glob.sql.cursor()

	with open("database_structs.sql", "r") as f:
		cur.executescript( f.read() )

	cur.close()
	print("[!] New sqlite database created")

if __name__ == "__main__":
	glob.app = make_app()

	if not path.isfile("wayback.db"):
		build_database()

	if glob.sql == None:
		glob.sql = glob.new_sql()

	print("Serving at %s:%s" % (glob.config["server"]["host"], glob.config["server"]["port"]))
	print("To stop server press CTRL + C")
	glob.app.listen(glob.config["server"]["port"], address=glob.config["server"]["host"])
	tornado.ioloop.IOLoop.instance().start()