from flask_restful import Resource, reqparse, abort, fields, marshal_with
from marshmallow import Schema, field
import json

class NotifySchema(Schema):
    client_id = fields.Str(required=True)
    secret = fields.Str(required=True)
    body = fields.Str(required=True)

class Notify(Resource):
    clients = None
    schema = None

    def __init__(self):
        self.schema = ReceiveSchema()
        with open("clients.json", "r") as clients_file:
            self.clients = json.load(clients_file)

    def post(self):
        errors = self.schema.validate(request.args)
        if errors:
            abort(400, str(errors))

        messages = []
        allow = False
        body = request.args.get("body")
        client_id = request.args.get("client_id")
        notify_queue = client_id + "-notify"
        if client_id in self.clients:
            client = self.clients.get(client_id)
            if request.args.get("secret") == client.get("secret"):
                allow = True

        if allow:
            connection = pika.BlockingConnection(pika.ConnectionParameters(host="localhost"))
            channel = connection.channel()
            channel.queue_declare(queue=notify_queue, durable=True)
            channel.basic_publish(exchange="", routing_key=notify_queue, body=body)
            deliver_connection.close()