from http.server import HTTPServer, SimpleHTTPRequestHandler
from json import dumps
import socketserver
import os
import sys

PORT = os.environ.get('PORT', 5000)

print(len(sys.argv))

if len(sys.argv) > 1:
    PORT = sys.argv[1]

from predict import predict
import json

print("hi")

class GetHandler(SimpleHTTPRequestHandler):
  def _send_cors_headers(self):
      """ Sets headers required for CORS """
      self.send_header("Access-Control-Allow-Origin", "*")
      self.send_header("Access-Control-Allow-Methods", "GET,POST,OPTIONS")
      self.send_header("Access-Control-Allow-Headers", "x-api-key,Content-Type")

  def send_dict_response(self, d):
      """ Sends a dictionary (JSON) back to the client """
      self.wfile.write(bytes(dumps(d), "utf8"))

  def do_OPTIONS(self):
      self.send_response(200)
      self._send_cors_headers()
      self.end_headers()

  def do_GET(self):
      self.send_response(200)
      self._send_cors_headers()
      self.end_headers()

      response = {}
      response["status"] = "OK"
      self.send_dict_response(response)

  def do_POST(self):
      if self.path == '/predict':
          length = int(self.headers.get('Content-Length'))
          body = json.loads(self.rfile.read(length))
      
          matchesIds = body['matchesToPredict_ids']
          print(matchesIds)
          predictions = predict(matchesIds)
  
          self.send_response(200)
          self._send_cors_headers()
          self.send_header('Content-Type', 'application/json')
          self.end_headers()
          self.wfile.write(json.dumps(predictions).encode(encoding='utf_8'))

          return 
      self.send_response(200)
      self._send_cors_headers()
      self.send_header("Content-Type", "application/json")
      self.end_headers()

      dataLength = int(self.headers["Content-Length"])
      data = self.rfile.read(dataLength)

      print(data)

      response = {}
      response["status"] = "OK"
      self.send_dict_response(response)
    
    
    


Handler=GetHandler

httpd = socketserver.TCPServer(("", int(PORT)), Handler)
print("Python web server listening on port {}...".format(PORT))
httpd.serve_forever()