#
# <one line to give the program's name and a brief idea of what it does.>
# SPDX-FileCopyrightText: 2022 gothic <email>
# SPDX-License-Identifier: GPL-3.0-or-later
#

from csharp_dao import cloudServiceDAO_pb2_grpc, cloudServiceDAO_pb2
from csharp_adminaxway import servicesAxwayAdmin_pb2_grpc, servicesAxwayAdmin_pb2
from flask import jsonify
import grpc
import base64
import json
import re

from google.protobuf.json_format import MessageToJson


class AxwaySrv:

    def main(request, PATH_APP):
        # data_form = (base64.b64decode(request.form['data_form_config_r']) if len(request.form.getlist('data_form_config_r')) > 0 else 'NOTFOUND')
        # json_results = json.loads(data_form)
        # organizacion = (json_results['organizacion']['name_org_axway'] if len(json_results['organizacion']) > 0 else 'NOTFOUND')
        # plan_id = (request.form['planid'] if len(request.form.getlist('planid')) > 0 else 'NOTFOUND')
        # user_vcd = (request.form['user_vcloud'] if len(request.form.getlist('user_vcloud')) > 0 else 'NOTFOUND')
        credential_dao = AxwaySrv.credentials_dao(PATH_APP)
        # credential_axway = AxwaySrv.credentials_axway(PATH_APP)
        result_insertdb = AxwaySrv.insertForm("", "gustavo.victoria", credential_dao)
        # result_axwaysrv = AxwaySrv.serviceContracted(data_form, credential_axway)
        # return result_axwaysrv
        return result_insertdb
    
    def credentials_dao(PATH_APP):
        with open(PATH_APP + "/App/certs/csharp_dao/" +"ca.pem", "rb") as fp:
            ca_cert = fp.read()

        creds = grpc.ssl_channel_credentials(ca_cert)
        return creds
        return grpc.ssl_channel_credentials(
            root_certificates=open(PATH_APP + "/App/certs/csharp_dao/" +"ca.pem", "rb").read(),#client_cert.ca_cert,
            private_key=open(PATH_APP + "/App/certs/csharp_dao/" +"server.key", "rb").read(), #client_cert.key,
            certificate_chain=open(PATH_APP + "/App/certs/csharp_dao/"+ "server.pem", "rb").read() #client_cert.cert
        )
    
    def credentials_axway(PATH_APP):
        return grpc.ssl_channel_credentials(
            root_certificates=open(PATH_APP + "/App/certs/csharp_adminaxway/" +"ca.pem", "rb").read(),#client_cert.ca_cert,
            private_key=open(PATH_APP + "/App/certs/csharp_adminaxway/" +"server.key", "rb").read(), #client_cert.key,
            certificate_chain=open(PATH_APP + "/App/certs/csharp_adminaxway/"+ "server.pem", "rb").read() #client_cert.cert
        )
    
    def insertForm(data_form, user_vcd, credential ):
        core_channel = grpc.secure_channel("localhost:8443", credentials=credential)
        stub_usr = cloudServiceDAO_pb2_grpc.servicioDAOServiceStub(core_channel)
        req_usr = cloudServiceDAO_pb2.GetUserVCDRequest(user_name=user_vcd)
        res_usr = stub_usr.getUserVCD(req_usr)

        #print(type(res_usr.users))

        re = MessageToJson(res_usr)

        return re

        if res_usr.response.response == "Couldn't find user information":
            return 'Imposible obtener id de usuario'
        else:
            id_usr_vcd = str(json.loads(res_usr.response.response)[0]['userID'])
        
        req_srv_contract = cloudServiceDAO_pb2.ContractedServicesRequest(
            backup_scheduled_id="",
            firewall_id="",
            plan_id=str(plan_id),
            user_id=id_usr_vcd,
        )
        res_srv_contract = stub_usr.getSaveFormAxwayService(req)

        req = cloudServiceDAO_pb2.SaveFormAxwayServiceRequest(form = data_form, id_user = "0")
        res = stub_usr.getSaveFormAxwayService(req)

        return jsonify(res.response.response)
    
    def serviceContracted(data_form, credential):
        core_channel = grpc.secure_channel("localhost:8443", credentials=credential)
        stub = servicesAxwayAdmin_pb2_grpc.ServiceAxwayAdminStub(core_channel)
        req = servicesAxwayAdmin_pb2.contractedServiceRequest(fromRegistro = data_form)
        res = stub.contractedService(req)
        ''' 
            Return message in service axway 
            {"errors":[{"code":102,"message":"Organization already exists"}]}
        '''
        print(res.response.response)
        result = re.search(r"{.*}", res.response.response).group()
        return result
        # if result[0] == 'Error al crear organizacion':
        #     return json.loads(result[1])
