#!/bin/env python3
from flask import Flask, request, jsonify
import websocket
import json
import yaml
import random
import threading
from pprint import pprint

__version__ = "2.0.0b2"
versionstring='Taurix TellMe server v' + __version__

app = Flask(__name__)
lock = threading.Lock()

ws = None
uri = "ws://localhost:5080"
ws = websocket.create_connection(uri)

hooks = {}
with open(r'/etc/tellme/hooks.yml') as hooksfile:
    hooks = yaml.load(hooksfile, Loader=yaml.FullLoader)

def sendmessage(target, message):
    global ws
    print("Sendmessage %s called to %s" % (message, target))
    msg = ("%s %s" % (target, message))

    # Create a unique correlation ID
    command = {
        "corrId": f"id{random.randint(0, 999999)}",
        "cmd": msg,
    }
    json_command = json.dumps(command)

    """ Connects to WebSocket server, sends a message, and returns the response """
    if ws is None:
        uri = "ws://localhost:5080"
        ws = websocket.create_connection(uri)  # Blocking WebSocket connection

    ws.send(json_command)  # Send message to WebSocket
    responsejson = ws.recv()  # Receive response
    response = json.loads(responsejson)
    # ws.close()

    for chatitem in response['resp']['chatItems']:
        statusdict = chatitem['chatItem']['meta']['itemStatus']
        try:
            status = statusdict['sndProgress']
        except KeyError:
            print("FAILED")
            pprint(chatitem)
            status = 'FAILED'
        else:
            smessage = chatitem['chatItem']['meta']['itemText']
            print("Message '%s' sent over websocket to %s, status was %s" % (smessage, target, status))

        if status == 'complete':
            # if smessage != message:
            #     print("Sent duplicate message, FAIL")
            #     return False
            # else:
            return True
        else:
            return False


@app.route("/webhook/<id>", methods=['POST'])
def webhook_receiver(id):
    print("Webhook id %s" % (id))
    data = request.json  # Get the JSON data from the incoming request
    # Process the data and perform actions based on the event
    print("Received webhook data:", data)

    target = None
    for key, value in hooks.items():
        if str(key) == str(id):
            target = value

    if target is not None:
        print(target)
        with lock:
            sendmessage(target, data.get('message'))
    else:
        print("No target found, dropping message")

    return jsonify({'message': 'Webhook received successfully'}), 200


if __name__ == '__main__':
    print("Started %s" % (versionstring))
    app.run()