#
# <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 flask import jsonify
import grpc
import base64
import json
import re

from google.protobuf.json_format import MessageToJson

import smtplib,os,mimetypes
from email import encoders
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase

#SERVER="smtp.gmail.com"
SERVER="192.168.98.221"
# SERVER="172.20.40.10"
SENDER_ADDRESS = "Alertas SGM <alertas_sgm@triara.com>"


class WSOA:

    to_mail = []

    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)
        #return json_results
        WSOA.to_mail = [json_results['email_user_woa']]
        subject = 'Solicitud de acceso a portal Workspace One Access'
        get_content_tmp: str
        with open(PATH_APP + "/App/views/templates/tmpl_email.html", "rb") as tmp:
            get_content_tmp = tmp.read()
        msg_html: str
        msg_html = get_content_tmp.decode("utf-8").replace("\n", "").replace("\t", "").replace("\r", "")\
            .replace("{HEADER}", "<h2>Solicitud de acceso a servicio </h2><h2><b>Workspace One Access</b></h2>")\
            .replace("{BODY}", 
                """
                <p>Por medio del presente se ha solicitado una cuenta de acceso al portal de Workspace One Access con los siguientes datos:</p>
                <p>
                    <span>Nombre: <b>"""+ json_results['name_user_woa'] +" "+ json_results['lastname_user_woa'] +"""</b></span><br>
                    <span>Nombre de usuario: <b>"""+ json_results['username_user_woa'] +"""</b></span><br>
                    <span>Correo Electronico: <b>"""+ json_results['email_user_woa'] +"""</b></span>
                </p>
                """
            )\
            .replace("{FOOTER}", 
                """
                    <p style="font-size:12px;line-height:18px;padding-top:20px;font-family:Helvetica,Arial,sans-serif;" align="center">
				    Este mensaje fue dirigido a Mesa de ayuda para su correspondiente proceso.
                    <br>Este correo es enviado de forma automática, por favor no responda a esta dirección.
				    </p>
                """
            )
        WSOA.send_mail(SENDER_ADDRESS,WSOA.to_mail,subject,SERVER,msg_html,None)
        return {'valid': True, 'message': 'Se envia correo satisfactoriamente', 'class': 'alert-success'}
        # 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])
    
    def send_mail(from_mail:str=SENDER_ADDRESS,to_mail:list=[],subject:str="",smtp_server:str=SERVER,msg_html:str="",files_path=None):
    
        # Create message container - the correct MIME type is multipart/alternative.

        # print("SERVER *****"+ SERVER)
        msg = MIMEMultipart('alternative')
        msg['Subject'] = subject
        msg['From'] = from_mail
        msg['To'] = ", ".join(to_mail)

        part1 = MIMEText(msg_html, 'html')
        msg.attach(part1)

        for file_path in files_path or []:
            with open(file_path, "rb") as fp:
                part = MIMEBase('application', "octet-stream")
                part.set_payload((fp).read())
                # Encoding payload is necessary if encoded (compressed) file has to be attached.
                encoders.encode_base64(part)
                part.add_header('Content-Disposition', "attachment; filename= %s" % os.path.basename(file_path))
                msg.attach(part)

        s = smtplib.SMTP(SERVER)

        # s.starttls() 
        # s.login('gvictoria0702@gmail.com', 'ebcsdpwwquhodvjt')

        s.sendmail(from_mail, to_mail, msg.as_string())
        s.quit()
