import requests, json


class ParsianWebcoIr:
    """
        token
        TemplateID
        MessageVars
        Receiver
        delay
    """
    API_KEY = None
    HEADERS = {"Content-Type": "application/x-www-form-urlencoded"}
    def __init__(self, mobile, options, *args, **kwargs):
        self.RECEIVER = mobile
        if options and 'api_key' in options:
            self.API_KEY = options['api_key']

    def send_message(self, message, template_id):
        try:
            api_url = 'https://api.parsianwebco.ir/webservice-send-sms/send'
            data = {
                'token': self.API_KEY,
                'TemplateID': template_id,
                'MessageVars': message,
                'Receiver': self.RECEIVER,
                'delay': 1
            }
            return json.loads(requests.post(url=api_url, data=data, headers=self.HEADERS).content)
            """
                response:
                    status:
                        200 ok
                        100 faild
                        401 no authenticated
            """
        except:
            return False
    
    def generate_response(self, api_response, mobile_number, message_text):
        from rest_framework.status import HTTP_200_OK, HTTP_502_BAD_GATEWAY, HTTP_401_UNAUTHORIZED

        if isinstance(api_response, dict) and 'status' in api_response:
            obj_status = api_response['status']
            if api_response['status'] == 200:
                response_data = {'receiver': mobile_number, 'message': message_text}
                response_status_code = HTTP_200_OK
                is_successfully = True
            elif api_response['status'] == 100:
                response_data = {'details': 'The SMS service provider was unable to process the request.'}
                response_status_code = HTTP_502_BAD_GATEWAY
                is_successfully = False
            elif api_response['status'] == 401:
                response_data = {'details': 'Authentication is not accepted, check your token...'}
                response_status_code = HTTP_401_UNAUTHORIZED
                is_successfully = False

        return is_successfully, {'data': response_data, 'obj_status': obj_status, 'status': response_status_code}
