from all_paw_care.invoice_ninja import API_TOKEN
from all_paw_care.invoice_ninja import BASE_URL
from all_paw_care.invoice_ninja.mappings.client import Client

import requests

class Clients(object):
    CLIENTS_URL = '{}/clients'.format(BASE_URL)
    HEADERS = {'X-API-TOKEN': API_TOKEN}

    def __build_sort_params(self, sort: dict):
        sort_params = {'sort': str()}
        is_first_entry = True
        for option in sort.keys():
            if is_first_entry:
                sort_params['sort'] += '{}|{}'.format(option, sort[option])
                is_first_entry = False

            else:
                sort_params['sort'] += ' {}|{}'.format(option, sort[option])

        return sort_params

    def __client_from_dict(self, client: dict):
        return Client(client_id=client['id'],
                name=client['name'],
                address=client['address1'],
                city=client['city'],
                state=client['state'],
                postal_code=client['postal_code'],
                phone=client['phone'],
                email=client['contacts'][0]['email'],
                pets=client['custom_value1'])

    def __clients_from_response(self, response: requests.Response):
        clients = list()
        for client_dict in response.json()['data']:
            clients.append(self.__client_from_dict(client_dict))

        return clients

    def list_client(self, client_id: str = None):
        """
            Get client based on client id.
        """
            
        if client_id:
           request_url = '{}/{}'.format(self.CLIENTS_URL, client_id)
           response = requests.get(url=request_url,
                    headers=self.HEADERS)

           if response.ok:
               return self.__client_from_dict(response.json()['data'])

        return None

    def list_clients(self, include: str = 'activities',
            sort: dict = dict(), status: str = 'active',
            name: str = None):
        """
            Get list of clients.
        """

        request_params = dict()

        # Add sort parameters to request
        if len(sort) > 0:
            request_params.update(self.__build_sort_params(sort))

        # Add include parameters to request
        request_params.update({'include': include})

        # Add status parameters to request
        request_params.update({'status': status})

        # Add name parameters to request
        if name:
            request_params.update({'name': name})

        # Check is request should be sent with parameters
        if len(request_params) > 0:
            response = requests.get(url=self.CLIENTS_URL,
                    params=request_params,
                    headers=self.HEADERS)
        else:
            response = requests.get(url=self.CLIENTS_URL,
                    headers=self.HEADERS)

        if response.ok:
            return self.__clients_from_response(response)

        else:
            return None

