import json
import os
import http.client
import requests

from urllib.parse import urlparse
from huaweicloudsdkcore.auth.credentials import Credentials
from huaweicloudsdkcore.sdk_request import SdkRequest
from huaweicloudsdkcore.signer.algorithm import SigningAlgorithm

"""
 Example of Invoking the batchSendDiffSms Interface to Send an SMS Message.
"""


class BatchSendDiffSms:

    def __init__(self):
        pass

    @staticmethod
    def main(args):
        print("Start HUAWEI CLOUD MSGSMS SEND SMS Python Demo...")

        """
         Send an SMS message using a special AK/SK authentication algorithm.
         When the MSGSMS is used to send SMS messages, the AK is app_key, and the SK is app_secret.
         There will be security risks if the app_key/app_secret used for authentication is directly written into code.
         We suggest encrypting the app_key/app_secret in the configuration file or environment variables for storage.
         In this sample, the app_key/app_secret is stored in environment variables for identity authentication.
         Before running this sample, set the environment variables CLOUD_SDK_MSGSMS_APPKEY and CLOUD_SDK_MSGSMS_APPSECRET.
         CLOUD_SDK_MSGSMS_APPKEY indicates the application key (app_key), and CLOUD_SDK_MSGSMS_APPSECRET indicates the application secret (app_secret).
         You can obtain the value from Application Management on the console or by calling the open API of Application Management.
        """
        if "CLOUD_SDK_MSGSMS_APPKEY" not in os.environ or "CLOUD_SDK_MSGSMS_APPSECRET" not in os.environ:
            print("Please config the environment CLOUD_SDK_MSGSMS_APPKEY and CLOUD_SDK_MSGSMS_APPSECRET first!")
            return

        ak = os.environ["CLOUD_SDK_MSGSMS_APPKEY"]
        sk = os.environ["CLOUD_SDK_MSGSMS_APPSECRET"]

        print("----Use POST /sms/batchSendDiffSms/v1 send msg now.")
        if BatchSendDiffSms.send_sms_using_diff(ak, sk) == http.client.OK:
            print("----batchSendDiffSms success.")
        else:
            print("---batchSendDiffSms failed.")

    @staticmethod
    def send_sms_using_diff(ak, sk):
        # This api_address of this example is of Beijing 4. Replace it with the actual value.
        # For detail, please refer to: https://support.huaweicloud.com/api-msgsms/sms_05_0019.html
        api_address = "https://smsapi.cn-north-4.myhuaweicloud.com/sms/batchSendDiffSms/v1"

        """
           Construct the message body of the sample code.
           For details about how to construct a body, see the API description.
           Sample is:
            {
                "from": "8824110605***",
                "statusCallback": "https://test/report",
                "smsContent": [{
                        "to": ["+86137****3774", "+86137****3775"],
                        "templateId": "1d18a7f4e1b84f6c8fc1546b48b3baea",
                        "templateParas": ["1", "23", "e"]
                    },
                    {
                        "to": ["+86137****3777"],
                        "templateId": "7824a51b3cc34976919a5418f637d0fb",
                        "templateParas": ["4", "5", "6"]
                    }
                ]
            }
         """
        json_data = json.dumps({'from': "8824110605***",
                                'statusCallback': "https://test/report",
                                'smsContent': [
                                    {'to': ["+86137****3774", "+86137****3775"],
                                     'templateId': "1d18a7f4e1b84f6c8fc1546b48b3baea",
                                     'templateParas': ["1", "23", "e"],
                                     },
                                    {'to': ["+86137****3777"],
                                     'templateId': "7824a51b3cc34976919a5418f637d0fb",
                                     'templateParas': ["4", "5", "6"],
                                     }]
                                }).encode('ascii')

        parsed_url = urlparse(api_address)
        headers = {
            "Content-type": "application/json;charset=utf8",
            "User-Agent": "huaweicloud-usdk-python/3.0",
            "Accept": "application/json",
            "Host": parsed_url.netloc
        }

        request = requests.Request(
            method="POST",
            url=api_address,
            headers=headers,
            data=json_data
        )

        # Signature operation of the batchSendDiffSms interface
        request = BatchSendDiffSms.sign_request(request, ak, sk)

        # send messages
        return BatchSendDiffSms.post_message(request)

    @staticmethod
    def sign_request(request, ak, sk):
        # The SDK signature algorithm is invoked. The original request needs to be converted into an SDK request for signature.
        parsed_url = urlparse(request.url)
        sdk_request = SdkRequest(method=request.method,
                                 schema=parsed_url.scheme,
                                 host=parsed_url.netloc,
                                 resource_path=parsed_url.path,
                                 uri=parsed_url.path,
                                 header_params=request.headers,
                                 query_params=[],
                                 body=request.data,
                                 signing_algorithm=SigningAlgorithm.HMAC_SHA256)

        """The signature algorithm uses the AK and SK signature algorithms provided by HUAWEI CLOUD IAM and API 
        Gateway. Signature algorithm implementation. The capabilities provided by the SDK are used here. Developers 
        can also use the signature capability provided by HUAWEI CLOUD APIG. For details, see the following website: 
        https://support.huaweicloud.com/devg-apisign/api-sign-sdk-python.html For the signature operation of an 
        interface, the signature must contain the body."""
        self = Credentials(ak, sk)
        signer_cls = self._SIGNER_CASE.get(SigningAlgorithm.HMAC_SHA256)
        if not signer_cls:
            return None

        sdk_request = signer_cls(self).sign(sdk_request)

        for header_param in sdk_request.header_params:
            request.headers[header_param] = sdk_request.header_params[header_param]
        return request

    @staticmethod
    def post_message(request):
        session = requests.Session()
        try:
            prepared_request = session.prepare_request(request)

            # To prevent API invoking failures caused by HTTPS certificate authentication failures, ignore the
            # certificate trust issue to simplify the sample code, set verify to False.
            # Note: Do not ignore the TLS certificate verification in the commercial version.
            response = session.send(prepared_request, verify=False, timeout=5)
            print("Response status code:", response.status_code)
            print("Response content:", response.text)
            return response.status_code
        except requests.exceptions.HTTPError as http_err:
            print(f'HTTP error occurred: {http_err}')
        except Exception as err:
            print(f'An error occurred: {err}')
        finally:
            session.close()

        return http.client.INTERNAL_SERVER_ERROR


if __name__ == "__main__":
    BatchSendDiffSms().main(any)