from gevent import pywsgi
from flask import Flask, request, send_from_directory, render_template, jsonify
import os
import pytz
import systime

app = Flask(__name__)

@app.route('/update/time', methods=['POST'])
def update_time():
    if request.is_json:
        try:
            json_data = request.get_json()
            print("update time:", json_data)
            ret = systime.update_system_datetime(json_data["timezone"], json_data["year"], json_data["month"], json_data["date"], json_data["hour"], json_data["minute"])
            if(ret == 0):
                response = jsonify({'message': 'Successfully update time'})
                response.status_code = 200
                return response
            else:
                response = jsonify({'message': 'Failed update time'})
                response.status_code = 400
                return response
        except:
            response = jsonify({'message': 'Invalid json'})
            response.status_code = 400
            return response
    else:
        response = jsonify({'message': 'Required json'})
        response.status_code = 400
        return response

@app.route('/timezones', methods=['GET'])
def timezones():
    try:
        timezones_list = list(pytz.all_timezones)
        response = jsonify({
            'message': 'Successfully',
            'timezones': timezones_list
        })
        response.status_code = 200
        return response
    except Exception as e:
        response = jsonify({"message": str(e)})
        response.status_code = 500
        return response

@app.route('/heartbeat', methods=['GET'])
def heartbeat():
    response = jsonify({'message': 'Connected'})
    response.status_code = 200
    return response

def main():
    print("Starting server, listen on 18001...")
    # app.run(host='0.0.0.0', port=8000, debug=True)
    server = pywsgi.WSGIServer(('0.0.0.0', 18001), app)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("Server stopped by user")
        server.stop()

if __name__ == '__main__':
    main()