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

ns = api.namespace('authorization')

authorization_input_fields = api.model('resource', {
    'externalId': fields.String,
    'externalKey': fields.String,
})


@ns.route('/')
class Authorization(Resource):
    @api.marshal_with(authorization_input_fields)
    def get(self):
        return {
            "name": "asd"
        }

    @api.expect(authorization_input_fields)
    def post(self):
        appId = "ce5f2a5c-405f-47e0-8550-301468fcc8ff"
        data = request.json
        externalId = data.get("externalId")
        externalKey = data.get("externalKey")
        db = Database()
        exist = db.IsExist(externalId)
        if exist == 0:
            userToken = LogIn()
            thingId = CreateThing(userToken, externalId)
            thingKey = GetKey(userToken, thingId)
            pubChannelId = CreateChannel(userToken, "chanell" + thingId + "pub")
            ConnectToChannel(userToken, pubChannelId, thingId)
            ConnectToChannel(userToken, pubChannelId, appId)
            subChannelId = CreateChannel(userToken, "chanell" + thingId + "sub")
            ConnectToChannel(userToken, subChannelId, thingId)
            ConnectToChannel(userToken, subChannelId, appId)
            data = {
                "channel_pub_id": pubChannelId,
                "channel_sub_id": subChannelId,
                "thing_id": thingId,
                "thing_key": thingKey,
                "externalId": externalId,
                "externalKey": externalKey,
            }
            db.AddNewRpi(data)
            return {
                "channel_pub_id": pubChannelId,
                "channel_sub_id": subChannelId,
                "thing_id": thingId,
                "thing_key": thingKey,
            }

        else:
            config = db.GetRpi(externalId)
            return {
                "channel_pub_id": config['channel_pub_id'],
                "channel_sub_id": config['channel_sub_id'],
                "thing_id": config['thing_id'],
                "thing_key": config['thing_key'],
            }
