# coding: utf-8

"""
    marax-server-sdk

    Marax Server SDK to send transactional events from client server to marax server  # noqa: E501

    The version of the OpenAPI document: 0.3.0
    Contact: team@marax.ai
    Generated by: https://openapi-generator.tech
"""


from __future__ import absolute_import

import re  # noqa: F401

# python 2 and python 3 compatibility library
import six
import json
import jwt
from datetime import datetime

from marax_server_sdk.api_client import ApiClient
from marax_server_sdk.exceptions import (
    ApiTypeError,
    ApiValueError
)


class RewardApi(object):
    """NOTE: This class is auto generated by OpenAPI Generator
    Ref: https://openapi-generator.tech

    Do not edit the class manually.
    """

    def __init__(self, api_client=None):
        if api_client is None:
            api_client = ApiClient()
        self.api_client = api_client

    def process_event(self, client, **kwargs):  # noqa: E501
        """Perform reward post-processing  # noqa: E501

        Process events like ORDER_COMPLETED and do the necessary changes to the validity of the reward object (if applicable) (Eg., increasing the count of reward redeemed, changing reward status to redeemed)   # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async_req=True
        >>> thread = api.process_event(client, async_req=True)
        >>> result = thread.get()

        :param async_req bool: execute request asynchronously
        :param str client: Id of the client obtained from MARS dashboard (required)
        :param RequestBody request_body: Details of transactional event
        :param _preload_content: if False, the urllib3.HTTPResponse object will
                                 be returned without reading/decoding response
                                 data. Default is True.
        :param _request_timeout: timeout setting for this request. If one
                                 number provided, it will be total request
                                 timeout. It can also be a pair (tuple) of
                                 (connection, read) timeouts.
        :return: Response200
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        return self.process_event_with_http_info(client, **kwargs)  # noqa: E501

    def process_event_with_http_info(self, client, **kwargs):  # noqa: E501
        """Perform reward post-processing  # noqa: E501

        Process events like ORDER_COMPLETED and do the necessary changes to the validity of the reward object (if applicable) (Eg., increasing the count of reward redeemed, changing reward status to redeemed)   # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async_req=True
        >>> thread = api.process_event_with_http_info(client, async_req=True)
        >>> result = thread.get()

        :param async_req bool: execute request asynchronously
        :param str client: Id of the client obtained from MARS dashboard (required)
        :param RequestBody request_body: Details of transactional event
        :param _return_http_data_only: response data without head status code
                                       and headers
        :param _preload_content: if False, the urllib3.HTTPResponse object will
                                 be returned without reading/decoding response
                                 data. Default is True.
        :param _request_timeout: timeout setting for this request. If one
                                 number provided, it will be total request
                                 timeout. It can also be a pair (tuple) of
                                 (connection, read) timeouts.
        :return: tuple(Response200, status_code(int), headers(HTTPHeaderDict))
                 If the method is called asynchronously,
                 returns the request thread.
        """

        local_var_params = locals()

        all_params = ['client', 'request_body']  # noqa: E501
        all_params.append('async_req')
        all_params.append('_return_http_data_only')
        all_params.append('_preload_content')
        all_params.append('_request_timeout')

        for key, val in six.iteritems(local_var_params['kwargs']):
            if key not in all_params:
                raise ApiTypeError(
                    "Got an unexpected keyword argument '%s'"
                    " to method process_event" % key
                )
            local_var_params[key] = val
        del local_var_params['kwargs']
        # verify the required parameter 'client' is set
        if self.api_client.client_side_validation and ('client' not in local_var_params or  # noqa: E501
                                                        local_var_params['client'] is None):  # noqa: E501
            raise ApiValueError("Missing the required parameter `client` when calling `process_event`")  # noqa: E501

        collection_formats = {}

        path_params = {}
        if 'client' in local_var_params:
            path_params['client'] = local_var_params['client']  # noqa: E501

        query_params = []

        header_params = {}

        form_params = []
        local_var_files = {}

        body_params = None
        if 'request_body' in local_var_params:
            body_params = local_var_params['request_body']
        # HTTP header `Accept`
        header_params['Accept'] = self.api_client.select_header_accept(
            ['application/json'])  # noqa: E501

        # HTTP header `Content-Type`
        header_params['Content-Type'] = self.api_client.select_header_content_type(  # noqa: E501
            ['application/json'])  # noqa: E501

        # Authentication setting
        auth_settings = ['ApiKeyAuth']  # noqa: E501

        return self.api_client.call_api(
            '/reward/v1/{client}/post-process', 'POST',
            path_params,
            query_params,
            header_params,
            body=body_params,
            post_params=form_params,
            files=local_var_files,
            response_type='Response200',  # noqa: E501
            auth_settings=auth_settings,
            async_req=local_var_params.get('async_req'),
            _return_http_data_only=local_var_params.get('_return_http_data_only'),  # noqa: E501
            _preload_content=local_var_params.get('_preload_content', True),
            _request_timeout=local_var_params.get('_request_timeout'),
            collection_formats=collection_formats)
    def reward_checker(self,current_cart_state,jwt_token,client_key):

        def objects_equal(o1, o2):
            if(o1==o2):
                return True
            else:
                return False
        
        def array_equal(ar1, ar2):
            if(ar1==None and ar2==None):
                return True
            if(len(ar1) != len(ar2)):
                return False
            flag2 = 1
            for i in range(len(ar1)):
                flag1 = 0
                for j in range(len(ar2)):
                    if(objects_equal(ar1[i], ar2[j])):
                        flag1 = 1
                        break
                if(flag1 == 0):
                    flag2 = 0
                    break
            if(flag2 == 0):
                return False
            else:
                return True

        try:
            decoded=jwt.decode(jwt_token, client_key, algorithms='RS512',verify=True)
        except Exception as e:
            return(
                json.dumps(
                    {
                        "isValid":False,
                        "message":"Invalid JWT",
                        "reward": None
                }))
        try:
            verified=0
            if(isinstance(current_cart_state,str)):
                current_cart_state=json.loads(current_cart_state)

            if(current_cart_state["maraxId"]==decoded["maraxId"]):
                verified+=1
            else:
                # print("hello")
                raise Exception("idMatchError")
            if(current_cart_state["paymentMode"]==decoded["paymentMode"]):
                verified+=1
            else:
                raise Exception("paymentModeMatchError")
            if(objects_equal(current_cart_state["totalOrderPrice"],decoded["totalOrderPrice"])):
                verified+=1
            else:
                # print("hell")
                raise Exception("orderPriceMatchError")
            if(objects_equal(current_cart_state["totalCartPrice"],decoded["totalCartPrice"])):
                verified+=1
            else:
                raise Exception("cartPriceMatchError")
            if(objects_equal(current_cart_state["totalDiscount"],decoded["totalDiscount"])):
                verified+=1
            else:
                raise Exception("discountMatchError")
            if(array_equal(current_cart_state["fulfillment"],decoded["fulfillment"])):
                verified+=1
            else:
                raise Exception("fulfillmentMatchError")
            if(array_equal(current_cart_state["products"],decoded["products"])):
                verified+=1
            else:
                raise Exception("productMatchError")
            if(datetime.utcnow()<=datetime.strptime(decoded["reward"]["expiry"],'%Y-%m-%dT%H:%M:%S.%fZ')):
                verified+=1
            else:
                raise Exception("rewardExpiredError")
            # return("verified: "+verified)
            if(verified==8):
                return(json.dumps(
                    {
                        "isValid":True,
                        "reward":decoded["reward"],
                        "message":"success"
                }))
       
        except Exception as err:
            if(str(err)=="idMatchError"):
                return(
                    json.dumps(
                        {
                            "isValid":False,
                            "message":"Marax Id not matching!",
                            "reward": None
                    }))
        
            elif(str(err)=="paymentModeMatchError"):

                return(
                    json.dumps(
                        {
                            "isValid":False,
                            "message":"Payment Mode not matching!",
                            "reward": None
                }))

            elif(str(err)=="orderPriceMatchError"):
                return(
                    json.dumps(
                        {
                            "isValid":False,
                            "message":"Total Order Price not matching!",
                            "reward": None
                }))

            elif(str(err)=="cartPriceMatchError"):
                return(
                    json.dumps(
                        {
                            "isValid":False,
                            "message":"Total Cart Price not matching!",
                            "reward": None
                }))

            elif(str(err)=="discountMatchError"):
                return(
                    json.dumps(
                        {
                            "isValid":False,
                            "message":"Total Discount not matching!",
                            "reward": None
                }))

            elif(str(err)=="fulfillmentMatchError"):

                return(
                    json.dumps(
                        {
                            "isValid":False,
                            "message":"Fulfillment not matching!",
                            "reward": None
                }))

            elif(str(err)=="productMatchError"):

                return(
                    json.dumps(
                        {
                            "isValid":False,
                            "message":"Cart Items not matching!",
                            "reward": None
                }))

            elif(str(err)=="rewardExpiredError"):

                return(
                    json.dumps(
                        {
                            "isValid":False,
                            "message":"Reward Expired!",
                            "reward": None
                }))

            else:

                return(
                    json.dumps(
                        {
                            "isValid":False,
                            "error":err,
                            "message":"Objects not matching/JWT Altered!",
                            "reward": None
                })
                   )
