import os
import subprocess
from http.server import BaseHTTPRequestHandler, HTTPServer
import urllib.parse
import mimetypes

class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        print(self.path)

        parsed_url = urllib.parse.urlparse(self.path)

        output_filename = parsed_url.path[1:]
        print(output_filename)

        # Open the converted file and read it
        with open(output_filename, 'rb') as f:
            content = f.read()

        # Send response headers
        self.send_response(200)
        mimetype, _ = mimetypes.guess_type(output_filename)
        self.send_header('Content-type', mimetype)
        self.send_header('Content-Length', len(content))
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Cross-Origin-Embedder-Policy', 'require-corp')
        self.send_header('Cross-Origin-Opener-Policy', 'same-origin')
        self.end_headers()

        # Send the content
        self.wfile.write(content)

        #os.remove(output_filename)
        #else:
        #    self.send_error(404, 'File Not Found: %s' % self.path)

def run(server_class=HTTPServer, handler_class=MyHandler):
    server_address = ('', 10464)
    httpd = server_class(server_address, handler_class)
    print('Starting httpd...')
    print('Serving on http://localhost:10464/flymusic.html')
    httpd.serve_forever()

if __name__ == '__main__':
    run()
