import subprocess
import pymongo
from flask import request
from flask_restplus import Resource
from flask_restplus import fields
from api.restplus import api
from api.authorizationHelper import LogIn, CreateThing, GetKey, CreateChannel, ConnectToChannel
from api.Database import Database
from serviceApi import startPubToAllRpi, startPubToChosenRpi, getAllActiveRpi

ns = api.namespace('dashboard')

payload_input_fields = api.model('resource', {
    'payload': fields.String
})

messages_input_fields = api.model('resource', {
    'messages': fields.String,
    "externalIds": fields.String
})

active_rpi_input_fields = api.model('resource', {
    'messages': fields.String
})


@ns.route('/')
class Authorization(Resource):
    @api.marshal_with(messages_input_fields)
    def get(self):
        db = Database()
        data = []
        externalIds = []
        for payload in db.GetAllPayload():
            data.append(payload["payload"].encode("ascii"))
            externalIds.append(payload["externalId"].encode("ascii"))
            print(payload)
        return {"messages": data, "externalIds": externalIds}

    @api.expect(payload_input_fields)
    def post(self):
        appId = "ce5f2a5c-405f-47e0-8550-301468fcc8ff"
        data = request.json
        payload = data.get("messages")
        print(payload)
        externalId = data.get("externalId")
        if externalId in ["all", "ALL", "All"]:
            startPubToAllRpi(payload)
        else:
            startPubToChosenRpi(payload, externalId)
        return {"response": "ok"}


@ns.route('/active/')
class ActiveRpi(Resource):
    @api.marshal_with(active_rpi_input_fields)
    def get(self):
        data = []
        activeRpi = getAllActiveRpi()
        for rpi in activeRpi:
            data.append(rpi.message)
        return {"messages": data}
