from gevent import monkey
monkey.patch_all()

from flask import Flask
from gevent.wsgi import WSGIServer
from base import BaseServer
import gevent
import os

class HTTPServer(BaseServer):
	subdirectory = "lol"
	directory = ""
	
	def __init__(self, parent):
		self.parent = parent
		self.directory = "../bins"
		self.app = Flask(__name__)
		self.flask_routes(self.app)

	def flask_routes(self, app):

		@app.route("/<path:file>")
		def get_file(file):
			if file in os.listdir(self.directory):
			    response = app.make_response(open(self.directory + "/" + file).read())
			    response.headers['Content-Type'] = 'application/octet-stream'
			    response.headers['Content-Disposition'] = 'attachment; filename=' + file
			    return response
			else:
				return "Not found"

	def start(self, port, args):
		http_server = WSGIServer(('', port), self.app)
		def running_greenlet():
			try:
				http_server.serve_forever()
			except Exception as e:
				print("Error in HTTP server: %s" % (str(e)))
		return gevent.spawn(running_greenlet)
	def usage(self):
		return ""

	def default_port(self):
		return 8080

	def default_args(self):
		return ""
