import requests


class KavenegarCom:
    '''
    API_KEY
    receptor
    message
    sender
    '''
    API_KEY = None
    SENDER = None
    
    def __init__(self, mobile, options, *args, **kwargs):
        self.RECEIVER = mobile
        if options and 'api_key' in options:
            self.API_KEY = options['api_key']
            if 'from' in options:
                self.SENDER = options['from']
    
    def send_message_lookup(self, message, template_id, **kwargs):
        try:
            api_url = f'https://api.kavenegar.com/v1/{self.API_KEY}/verify/lookup.json'
            message = ''.join(list(map(lambda x: x if x != ' ' else '-', message.strip())))
            data = {
                'receptor': self.RECEIVER,
                'template': template_id,
                'token': message,
            }
            if kwargs.get('token2'):
                data['token2'] = ''.join(list(map(lambda x: x if x != ' ' else '-', kwargs.get('token2').strip())))

            if kwargs.get('token3'):
                data['token3'] = ''.join(list(map(lambda x: x if x != ' ' else '-', kwargs.get('token3').strip())))

            if kwargs.get('token10'):
                data['token10'] = kwargs.get('token10').strip()

            if kwargs.get('token20'):
                data['token20'] = kwargs.get('token20').strip()

            response = requests.post(url=api_url, data=data)
            return response
            
        except Exception as e:
            print(str(e))
            return False

    def send_message(self, message):
        try:
            api_url = f'https://api.kavenegar.com/v1/{self.API_KEY}/sms/send.json'
            data = {
                'sender': self.SENDER,
                'receptor': self.RECEIVER,
                'message': message,
            }
            response = requests.post(url=api_url, data=data)
            return response
            """
                response:
                    messageid Unique identifier of this SMS (To know the status of the sent SMS, this value is the input to the Status method.)
                    status:
                        200   if status is 10 & 5 , message received.
                        400   The parameters are incomplete.
                        401   Account has been deactivated.
                        403   The API-Key identification code is not valid.
                        406   Empty mandatory parameters sent.
                        411   The recipient is invalid.
                        412   The sender is invalid.
                        413   The message is empty or the message length exceeds the allowed limit. The maximum length of the entire SMS text is 900 characters.
                        414   The request volume exceeds the allowed limit, sending SMS: maximum 200 records per call and status control: maximum 500 records per call
                        416   The originating service IP does not match the settings.
                        418   Your credit is not sufficient.
                        451   Excessive calls within a specific time period are restricted to IP addresses.
            """
        except Exception as e:
            print(str(e))
            return False
    
    def detect_tokens_from_data(self, data: dict):
        result = {}

        if 'token2' in data:
            result['token2'] = data.get('token2')
        if 'token3' in data:
            result['token3'] = data.get('token3')
        if 'token10' in data:
            result['token10'] = data.get('token10')
        if 'token20' in data:
            result['token20'] = data.get('token20')
        
        return result
    
    def generate_response(self, api_response):
        from rest_framework.status import HTTP_200_OK, HTTP_502_BAD_GATEWAY

        response_json = api_response.json()
        entries = response_json.get('entries', [])
        _return = response_json.get('return', {})

        if entries:
            response_data = entries[0]
            obj_status = response_data.get('status')
            if api_response.status_code == 200 and response_data.get('status') in [5, 10, 1]:
                response_data = {'receiver': response_data.get('receptor'), 'message': response_data.get('message'), 'messageid': response_data.get('messageid')}
                response_status_code = HTTP_200_OK
                is_successfully = True
            else:
                response_data = {'details': 'The SMS service provider was unable to process the request.', 'errorcode': response_data.get('status'), 'errortext': response_data.get('statustext'), 'message': response_data.get('message')}
                response_status_code = HTTP_502_BAD_GATEWAY
                is_successfully = False
        elif _return:
            obj_status = _return.get('status')
            response_data = {'details': 'The SMS service provider was unable to process the request.', 'message': _return.get('message')}
            response_status_code = HTTP_502_BAD_GATEWAY
            is_successfully = False
        
        return is_successfully, {'data': response_data, 'obj_status': obj_status, 'status': response_status_code}

