from flask import Flask, jsonify, request, Response
from flask_jwt_extended import create_access_token
from ..db.db import MongoDatabse
from datetime import datetime
from ..config import Config
import base64
import uuid

class RegisterOperations:

    def __init__(self):
        self.db = MongoDatabse()
        self.mimetype = 'application/json'
        self.config = Config().get_config()

    def register_user(self, username, password, description, email):

        mycol = self.db.get_col_by_name(self.db.capif_users)
        exist_user = mycol.find_one({"username": username})
        if exist_user:
            return jsonify("user already exists"), 409
        
        name_space = uuid.UUID(self.config["register"]["register_uuid"])
        user_uuid = str(uuid.uuid5(name_space, username))

        user_info = dict(uuid=user_uuid, username=username, password=password, description=description, email=email, onboarding_date=datetime.now())
        obj = mycol.insert_one(user_info)

        return jsonify(message="User registered successfully", uuid=user_uuid), 201

    def get_auth(self, username):

        mycol = self.db.get_col_by_name(self.db.capif_users)

        try:

            exist_user = mycol.find_one({"username": username})

            if exist_user is None:
                return jsonify("Not exister user with this credentials"), 400

            access_token = create_access_token(identity=(username + " " + exist_user["uuid"]))
            
            cert_file = open("register_service/certs/ca_root.crt", 'rb')
            ca_root = cert_file.read()
            cert_file.close()

            return jsonify(message="Token and CA root returned successfully", 
                            access_token=access_token, 
                            ca_root=ca_root.decode("utf-8"),
                            ccf_api_onboarding_url="api-provider-management/v1/registrations",
                            ccf_publish_url="published-apis/v1/<apfId>/service-apis",
                            ccf_onboarding_url="api-invoker-management/v1/onboardedInvokers",
                            ccf_discover_url="service-apis/v1/allServiceAPIs?api-invoker-id=",
                            ccf_security_url="capif-security/v1/trustedInvokers/<apiInvokerId>"), 200

        except Exception as e:
            return jsonify(message=f"Errors when try getting auth: {e}"), 500

    def remove_user(self, uuid):
        mycol = self.db.get_col_by_name(self.db.capif_users)

        try:
            mycol.delete_one({"uuid": uuid})
            

            # Request to the helper to delete invokers and providers


            return jsonify(message="User removed successfully"), 204
        except Exception as e:
            return jsonify(message=f"Errors when try remove user: {e}"), 500
        
    def get_users(self):
        mycol = self.db.get_col_by_name(self.db.capif_users)

        try:
            users=list(mycol.find({}, {"_id":0}))
            return jsonify(message="Users successfully obtained", users=users), 200
        except Exception as e:
            return jsonify(message=f"Error trying to get users: {e}"), 500

