from appservices.common.util import *

services = Blueprint("services",__name__)

def get_api_authentication_details(api_queryset):
    api_authentication_dict={}
    try:
        api_authentication_details = {
        "id": str(api_queryset.id),
        "apiName": api_queryset.apiName,
        "code": api_queryset.code,
        "isActive": api_queryset.isActive,
        "isUserWise": api_queryset.isUserWise,
        "transactionType": api_queryset.transactionType,
        "paramsList": api_queryset.paramsList,
        }
        if api_queryset.paramsList:
            api_authentication_dict["paramsList"] = api_queryset.paramsList
        else:
            api_authentication_dict["paramsList"] = []
    except Exception as e:
        app.logger.error(traceback.format_exc())
    return api_authentication_details


#Get api authentication details
@services.route("/api_authentication_details",methods=["POST"])
def api_authentication_details():
    data_status = {"responseStatus": 0, "result": ""}
    transactionAPIId = request.json.get("transactionAPIId","")
    try:
        if transactionAPIId:
            api_queryset = TransactionAPI.objects(id=transactionAPIId).first()
            if not api_queryset:
                data_status["result"] = "Invalid transaction API Id"
                return data_status
            api_authentication_data = get_api_authentication_details(api_queryset)

            data_status["responseStatus"] = 1
            data_status["result"] = "Authentication details fetched successfully"
            data_status["apiAuthenticationDetails"] = api_authentication_data
            return data_status
        else:
            data_status["result"] = "Required field is missing"
            return data_status
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"] = "Unable to get api authentication details"
        return data_status


@services.route("/view_all_services", methods=["GET", "POST"])
def view_all_services():
    print("view_all_services")
    data_status = {"responseStatus": 0, "result": ""}
    overallServicesList = []

    try:
        service_grouping_queryset = ServiceGrouping.objects(status__in=[1]).order_by("sorting").all()
        for each_grouping in service_grouping_queryset:
            servicesList = []
            service_grouping_dict = {
            "id":str(each_grouping.id),
            "serviceGroupingName":each_grouping.name,
            "sorting":each_grouping.sorting
            }
            categories_queryset = Categories.objects(
                serviceGroupingId=str(each_grouping.id),status__in=[1],displayInDashboard=True).order_by("-id").all()
            for each_category in categories_queryset:
                category_dict = {
                "id":str(each_category.id),
                "categoryName":each_category.categoryName,
                "image":"",
                "serviceType":"categories",
                "sorting":each_category.sorting,
                "comingsoon":each_category.comingsoon,
                "apiCode":"",
                "apiType":"",
                # "transactionAPIName":each_category.transactionAPIId.apiName,
                # "transactionAPIId":str(each_category.transactionAPIId.id),
                "serviceName":each_category.categoryName,
                "operatorName":""
                }
                try:
                    if each_category.serviceGroupingId:
                        category_dict["serviceGroupingId"] = str(each_category.serviceGroupingId.id)
                        category_dict["serviceGroupingName"] = each_category.serviceGroupingId.name
                    else:
                        category_dict["serviceGroupingId"] = ""
                        category_dict["serviceGroupingName"] = ""
                except:
                    category_dict["serviceGroupingId"] = ""
                    category_dict["serviceGroupingName"] = ""

                try:
                    if each_category.transactionAPIId:
                        category_dict["transactionAPIId"] = str(each_category.transactionAPIId.id)
                        category_dict["transactionAPIName"] = each_category.transactionAPIId.apiName
                    else:
                        category_dict["transactionAPIId"] = ""
                        category_dict["transactionAPIName"] = ""
                except:
                    category_dict["transactionAPIId"] = ""
                    category_dict["transactionAPIName"] = ""

                if each_category.image:
                    category_dict["image"] = domain+each_category.image
                else:
                    category_dict["image"] = ""

                if each_category.sorting:
                    category_dict["sorting"] = each_category.sorting
                else:
                    category_dict["sorting"] = ""

                servicesList.append(category_dict)

            services_queryset = Service.objects(
                serviceGroupingId=str(each_grouping.id), status__in=[1],displayInDashboard=True).order_by("-id").all()
            for each_service in services_queryset:
                service_dict = {
                "id":str(each_service.id),
                "serviceName":each_service.serviceName,
                "categoryId":str(each_service.categoryId.id),
                "categoryName":each_service.categoryId.categoryName,
                "image":"",
                "serviceType":"service",
                "sorting":each_service.sorting,
                "apiCode":"",
                "apiType":"",
                # "transactionAPIName":str(each_service.transactionAPIId.id),
                # "transactionAPIId":each_service.transactionAPIId.apiName,
                "operatorName":""
                }
                try:
                    if each_service.serviceGroupingId:
                        service_dict["serviceGroupingId"] = str(each_service.serviceGroupingId.id)
                        service_dict["serviceGroupingName"] = each_service.serviceGroupingId.name
                    else:
                        service_dict["serviceGroupingId"] = ""
                        service_dict["serviceGroupingName"] = ""
                except:
                    service_dict["serviceGroupingId"] = ""
                    service_dict["serviceGroupingName"] = ""

                try:
                    if each_service.transactionAPIId:
                        service_dict["transactionAPIId"] = str(each_service.transactionAPIId.id)
                        service_dict["transactionAPIName"] = each_service.transactionAPIId.apiName
                    else:
                        service_dict["transactionAPIId"] = ""
                        service_dict["transactionAPIName"] = ""
                except:
                    service_dict["transactionAPIId"] = ""
                    service_dict["transactionAPIName"] = ""

                if each_service.sorting:
                    service_dict["sorting"] = each_service.sorting
                else:
                    service_dict["sorting"] = ""

                if each_service.file:
                    service_dict["image"] = domain+each_service.file
                else:
                    service_dict["image"] = ""

                servicesList.append(service_dict)


            operators_queryset = Operators.objects(
                serviceGroupingId=str(each_grouping.id), status__in=[1],displayInDashboard=True).order_by("-id").all()
            for each_operator in operators_queryset:
                operator_dict = {
                "id":str(each_operator.id),
                "operatorName":each_operator.operatorName,
                "categoryId":str(each_operator.serviceId.categoryId.id),
                "categoryName":each_operator.serviceId.categoryId.categoryName,
                "isTpin":each_operator.serviceId.categoryId.isTpin,
                "serviceType":"operator",
                "sorting":each_operator.sorting,
                "apiCode":"",
                "serviceName":each_operator.serviceId.serviceName,
                "serviceId":str(each_operator.serviceId.id),
                }
                try:
                    if each_operator.serviceGroupingId:
                        operator_dict["serviceGroupingId"] = str(each_operator.serviceGroupingId.id)
                        operator_dict["serviceGroupingName"] = each_operator.serviceGroupingId.name
                    else:
                        operator_dict["serviceGroupingId"] = ""
                        operator_dict["serviceGroupingName"] = ""
                except:
                    operator_dict["serviceGroupingId"] = ""
                    operator_dict["serviceGroupingName"] = ""

                try:
                    if each_operator.transactionAPIId:
                        operator_dict["transactionAPIId"] = str(each_operator.transactionAPIId.id)
                        operator_dict["transactionAPIName"] = each_operator.transactionAPIId.apiName
                    else:
                        operator_dict["transactionAPIId"] = ""
                        operator_dict["transactionAPIName"] = ""
                except:
                    operator_dict["transactionAPIId"] = ""
                    operator_dict["transactionAPIName"] = ""

                if each_operator.apiType:
                    operator_dict["apiType"] = each_operator.apiType
                else:
                    operator_dict["apiType"] = ""

                if each_operator.payWithoutFetchAllowed:
                    operator_dict["payWithoutFetchAllowed"] = each_operator.payWithoutFetchAllowed
                else:
                    operator_dict["payWithoutFetchAllowed"] = False

                if each_operator.sorting:
                    operator_dict["sorting"] = each_operator.sorting
                else:
                    operator_dict["sorting"] = ""

                if each_operator.image:
                    operator_dict["image"] = domain+each_operator.image
                else:
                    operator_dict["image"] = ""

                servicesList.append(operator_dict)

            service_grouping_dict["servicesList"] = servicesList

            overallServicesList.append(service_grouping_dict)


            
        # overallServicesList.append(overallServiceDict)
        data_status["responseStatus"] = 1
        data_status["result"] = "Services data fetched successfully!"
        data_status["overallServicesList"] = overallServicesList
        return data_status

    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"] = "Unable to fetch services data!!"
        return data_status


@services.route("/category_based_services_list",methods=["POST"])
def category_based_services_list():
    data_status = {"responseStatus": 0, "result": ""}
    categoryId = request.json.get("categoryId","")

    if not categoryId:
        data_status["result"] = "Required fields are missing!!"
        return data_status
    try:
        category_queryset = Categories.objects(id=categoryId,status__in=[1]).first()
        if not category_queryset:
            data_status["result"]="Invalid category id!!"
            return data_status
        servicesList = []
        services_queryset = Service.objects(
            categoryId=str(category_queryset.id),
            # transactionAPIId=str(category_queryset.transactionAPIId.id),
            status__in=[1]
            ).order_by("-id").all()
        for each_service in services_queryset:
            service_dict = fetching_service_details(each_service)
            servicesList.append(service_dict)

        data_status["responseStatus"] = 1
        data_status["result"] = "Category based services data fetched successfully!"
        data_status["servicesList"] = servicesList
        return data_status
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"] = "Unable to fetch services data!!"
        return data_status

@services.route("/service_based_operators_list",methods=["POST"])
def service_based_operators_list():
    data_status = {"responseStatus": 0, "result": ""}
    serviceId = request.json.get("serviceId","")

    if not serviceId:
        data_status["result"] = "Required fields are missing!!"
        return data_status
    try:
        service_queryset = Service.objects(id=serviceId,status__in=[1]).first()
        if not service_queryset:
            data_status["result"]="Invalid service id!!"
            return data_status
        operatorsList = []
        operators_queryset = Operators.objects(
            serviceId=str(service_queryset.id),
            # transactionAPIId=str(service_queryset.transactionAPIId.id),
             status__in=[1]
             ).order_by("-id").all()
        for each_operator in operators_queryset:
            operator_dict = fetching_operator_details(each_operator)
            operatorsList.append(operator_dict)

        data_status["responseStatus"] = 1
        data_status["result"] = "Service based operators data fetched successfully!"
        data_status["operatorsList"] = operatorsList
        return data_status
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"] = "Unable to fetch operators data!!"
        return data_status

@services.route("/operator_based_operator_parameters_list",methods=["POST"])
def operator_based_operator_parameters_list():
    data_status = {"responseStatus": 0, "result": ""}
    operatorId = request.json.get("operatorId","")

    if not operatorId:
        data_status["result"] = "Required fields are missing!!"
        return data_status
    try:
        operator_queryset = Operators.objects(id=operatorId,status__in=[1]).first()
        if not operator_queryset:
            data_status["result"]="Invalid operator id!!"
            return data_status

        transactionAPIId = str(operator_queryset.transactionAPIId.id)

        operatorParametersList = []
        operator_parameters_queryset = OperatorParameter.objects(
            operatorId=str(operator_queryset.id),
            transactionAPIId=transactionAPIId,
            status__in=[1]
            ).order_by("sort").all()
        for each_operator_parameter in operator_parameters_queryset:
            operator_parameter_dict = fetching_operator_based_parameter_details(each_operator_parameter)
            operatorParametersList.append(operator_parameter_dict)

        data_status["responseStatus"] = 1
        data_status["result"] = "Operator based operator parameters data fetched successfully!"
        data_status["operatorParametersList"] = operatorParametersList
        return data_status
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"] = "Unable to fetch operator parameters data!!"
        return data_status

@services.route("/grouping_based_sub_parameters_list",methods=["POST"])
def grouping_based_sub_parameters_list():
    data_status = {"responseStatus": 0, "result": ""}
    groupingId = request.json.get("groupingId","")

    if not groupingId:
        data_status["result"] = "Required fields are missing!!"
        return data_status
    try:
        grouping_queryset = OperatorGrouping.objects(id=groupingId,status__in=[1]).first()
        if not grouping_queryset:
            data_status["result"]="Invalid grouping id!!"
            return data_status

        # transactionAPIId = str(operator_queryset.transactionAPIId.id)

        subParametersList = []
        sub_parameters_queryset = SubParameters.objects(
            operatorGroupingId=str(grouping_queryset.id),
            status__in=[1]
            ).order_by("sort").all()
        for each_sub_parameter in sub_parameters_queryset:
            sub_parameter_dict = fetching_grouping_based_sub_parameter_details(each_sub_parameter)
            subParametersList.append(sub_parameter_dict)

        data_status["responseStatus"] = 1
        data_status["result"] = "Grouping based sub parameters data fetched successfully!"
        data_status["subParametersList"] = subParametersList
        return data_status
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"] = "Unable to fetch sub parameters data!!"
        return data_status

@services.route("/get_registration_details_list",methods=["POST"])
def get_registration_details_list():
    data_status = {"responseStatus": 0, "result": ""}
    userTypeId = request.json.get("userTypeId","")
    entityTypeId = request.json.get("entityTypeId","")

    print(request.json)
    print("(((((((((((((((request.json)))))))))))))))")

    registrationDataList = []
    if userTypeId and entityTypeId:
        try:
            registration_steps_queryset = RegistrationStep.objects(
                userTypeIdsList__in=[userTypeId],
                entityTypeIdsList__in=[entityTypeId],
                status__in=[1]).order_by('rank').all()
            print(registration_steps_queryset.count())
            if not registration_steps_queryset:
                data_status["result"]="Invalid user type or entity type id!!"
                return data_status

            for each_registration_step in registration_steps_queryset:
                registration_step_dict = {
                "id":str(each_registration_step.id),
                "stepName":each_registration_step.stepName,
                "label":each_registration_step.label,
                "rank":each_registration_step.rank,
                "isMandatory":each_registration_step.isMandatory,
                "isSignup":each_registration_step.isSignup,
                }  
                registration_fields_queryset = RegistrationFields.objects(
                    registrationStepId=str(each_registration_step.id),
                    userTypeIdsList__in=[userTypeId],
                    entityTypeIdsList__in=[entityTypeId],
                    ).order_by('rank').all()
                registrationFieldsList =[]
                for each_registration_field in registration_fields_queryset:
                    registration_field_dict = {
                    "id":str(each_registration_field.id),
                    "fieldName":each_registration_field.fieldName,
                    "fieldType":each_registration_field.fieldType,
                    "label":each_registration_field.label,
                    "rank":each_registration_field.rank,
                    "webRegex":each_registration_field.webRegex,
                    "mobileRegex":each_registration_field.mobileRegex,
                    "validationMessage":each_registration_field.validationMessage,
                    "isGroup":each_registration_field.isGroup,
                    "isDocumentGroup":each_registration_field.isDocumentGroup,
                    "hasCaps":each_registration_field.hasCaps,
                    "isVerified":each_registration_field.isVerified,
                    "isSignup":each_registration_field.isSignup,
                    }
                    if each_registration_field.isGroup:
                        registration_field_dict["groupType"] = each_registration_field.groupType
                    else:
                        registration_field_dict["groupType"] = ""

                    if each_registration_field.isDocumentGroup:
                        registration_field_dict["documentGroupName"] = each_registration_field.documentGroupId.name
                    else:
                        registration_field_dict["documentGroupName"] = ""

                    registrationFieldsList.append(registration_field_dict)
                registration_step_dict["registrationFieldsList"]=registrationFieldsList
                registrationDataList.append(registration_step_dict)

            data_status["responseStatus"] = 1
            data_status["result"] = "Registration masters data fetched successfully!"
            data_status["registrationDataList"] = registrationDataList
            return data_status
        except Exception as e:
            app.logger.error(traceback.format_exc())
            data_status["result"] = "Unable to fetch registration masters data!!"
            return data_status
    else:
        data_status["result"] = "Required fields are missing!!"
        return data_status


@services.route("/view_all_payment_modes",methods=["POST"])
def view_all_payment_modes():
    data_status = {"responseStatus": 0, "result": ""}
    userId = request.json.get("userId","")

    try:
        paymentModesList = []
        payment_modes_queryset = PaymentMode.objects(status__in=[1]).order_by("-id").all()
        for each_payment_mode in payment_modes_queryset:
            paymentModeDict = fetching_payment_mode_details(each_payment_mode)
            paymentModesList.append(paymentModeDict)

        data_status["responseStatus"] = 1
        data_status["result"] = "Payment modes data fetched successfully!"
        data_status["paymentModesList"] = paymentModesList
        return data_status
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"] = "Unable to fetch payment modes data!!"
        return data_status

@services.route("/paymentmode_based_on_sub_paymentmode_list",methods=["POST"])
def paymentmode_based_on_sub_paymentmode_list():
    data_status = {"responseStatus": 0, "result": ""}
    paymentModeId = request.json.get("paymentModeId","")

    try:
        payment_mode_queryset = PaymentMode.objects(id=paymentModeId,status__in=[1]).first()
        if not payment_mode_queryset:
            data_status["result"]="Invalid payment mode id!!"
            return data_status

        subPaymentModesList = []
        sub_payment_modes_queryset = SubPaymentModes.objects(
            paymentModeId=str(payment_mode_queryset.id),
            status__in=[1]
            ).order_by("-id").all()
        for each_sub_payment_mode in sub_payment_modes_queryset:
            subPaymentModeDict = fetching_sub_payment_mode_details(each_sub_payment_mode)
            subPaymentModesList.append(subPaymentModeDict)

        data_status["responseStatus"] = 1
        data_status["result"] = "Paymentmode based sub paymentmodes data fetched successfully!"
        data_status["subPaymentModesList"] = subPaymentModesList
        return data_status
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"] = "Unable to fetch sub paymentmodes data!!"
        return data_status

@services.route("/config_payment_gate_ways_list",methods=["POST"])
def config_payment_gate_ways_list():
    data_status = {"responseStatus": 0, "result": ""}
    subPaymentModeId = request.json.get("subPaymentModeId","")

    try:
        sub_payment_mode_queryset = SubPaymentModes.objects(id=subPaymentModeId,status__in=[1]).first()
        if not sub_payment_mode_queryset:
            data_status["result"]="Invalid sub payment mode id!!"
            return data_status

        configPaymentGatewaysList = []
        config_payment_gateways_queryset = ConfigPaymentGateways.objects(
            subPaymentModeId=str(sub_payment_mode_queryset.id),
            status__in=[1]
            ).order_by("-id").all()
        for each_config_payment_gateway in config_payment_gateways_queryset:
            config_payment_gateway_dict = fetching_config_payment_gateway_details(each_config_payment_gateway)
            configPaymentGatewaysList.append(config_payment_gateway_dict)

        data_status["responseStatus"] = 1
        data_status["result"] = "Config payment gateways data fetched successfully!"
        data_status["configPaymentGatewaysList"] = configPaymentGatewaysList
        return data_status
    except Exception as e:
        app.logger.error(traceback.format_exc())
        data_status["result"] = "Unable to fetch config payment gateways data!!"
        return data_status