#!/usr/bin/env python3
"""
Very simple HTTP server in python for logging requests
Usage::
    ./server.py [<port>]
"""
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import logging
import os
import datetime
import base64

class S(BaseHTTPRequestHandler):

    def do_OPTIONS(self):
        self.send_response(200, "ok")

    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.end_headers()
        with open('data/schedule.json', 'r') as file:
          schedule_string = json.load(file)

        self.wfile.write(json.dumps(schedule_string).encode('utf-8'))

    def do_POST(self):

        content_length = int(self.headers['Content-Length'])
        request_raw = self.rfile.read(content_length)
        request_content = json.loads(request_raw)
        schedule = request_content['schedule']
        pw = request_content['pw']
        caption = request_content['caption']
        heading = request_content['heading']
        image = request_content['image']

        if pw != 'kurswerk':
          self.send_response(401)
          self.send_header('Content-Type', 'text/html')
          self.end_headers()
          self.wfile.write("Unauthorized".encode('utf-8'))

        schedule_and_caption = {}
        schedule_and_caption['schedule'] = schedule
        schedule_and_caption['caption'] = caption
        schedule_and_caption['heading'] = heading
        now = datetime.datetime.now()
        try:
          os.rename('data/schedule.json', 'data/schedule_{}.json'.format(now.strftime("%Y%m%d")))
        except Exception:
          logging.info('Backup exists, did not backup..')
          pass
        with open('data/schedule.json', 'w') as file:
          json.dump(schedule_and_caption, file)

        with open('data/schedule.jpg', 'wb') as f:
          f.write(base64.b64decode(image))

        self.send_response(200)
        self.send_header('Content-Type', 'text/html')
        self.end_headers()
        self.wfile.write("New schedule set".encode('utf-8'))


def run(server_class=HTTPServer, handler_class=S, port=8080):
    logging.basicConfig(level=logging.INFO)
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    logging.info('Starting httpd...\n')
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    logging.info('Stopping httpd...\n')

if __name__ == '__main__':
    from sys import argv

    if len(argv) == 2:
        run(port=int(argv[1]))
    else:
        run()
