from flask import jsonify, current_app
from flask_jwt_extended import create_access_token
from db.db import MongoDatabse
from datetime import datetime
from config import Config
import requests
import uuid
import os


class RegisterOperations:

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

    def register_user(self, user_info):

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

        user_info["uuid"] = user_uuid
        user_info["onboarding_date"]=datetime.now()
        mycol.insert_one(user_info)

        current_app.logger.debug(f"User with uuid {user_uuid} and username {user_info["username"]} registered successfully")

        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:
                current_app.logger.debug(f"No user exists with these credentials: {username}")
                return jsonify("No user exists with these credentials"), 400

            access_token = create_access_token(identity=(username + " " + exist_user["uuid"]))
            current_app.logger.debug(f"Access token generated for user {username} : {access_token}")
            
            cert_file = open("certs/ca_root.crt", 'rb')
            ca_root = cert_file.read()
            cert_file.close()

            current_app.logger.debug(f"Returning the requested information...")

            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:

            url = f"https://{self.config["ccf"]["url"]}{self.config["ccf"]["helper_remove_user"]}{uuid}"
            requests.delete(url, cert=("certs/superadmin.crt", "certs/superadmin.key"), verify="certs/ca_root.crt", timeout=int(os.getenv("TIMEOUT")))
            
            mycol.delete_one({"uuid": uuid})
            current_app.logger.debug(f"User with uuid {uuid} removed successfully")
            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

