# coding: utf-8

"""
    Yanport API

    ## À propos Voici quelques ressources qui vous aideront à explorer notre API, si vous avez des problèmes ou des demandes, veuillez contacter le [support](mailto:support@yanport.com). ## REST API Nos services webs utilisent le protocle **HTTPS** sur le port 443, tout accès en HTTP sur le port 80 est bloqué par notre pare-feu. Les échanges de données sont réalisés en **JSON**. ## Authentification Avant de commencer à explorer notre API, vous devez nous [contacter](https://www.yanport.com/contact) afin d'obtenir un [JSON Web Token](https://jwt.io) (**JWT**) qui vous permettra de vous identifier à chaque requêtes. ### JWT (header) La méthode privilégiée pour s'authentifier est de passer à chaque requêtes le token dans le header `Authorization: Bearer {{ JWT }}` en remplaçant `{{ JWT }}` par votre token. ### JWT (query param) Il est aussi possible de passer le token directement en query param de la requête `https://api.yanport.com/?token={{ JWT }}`. (_privilégié le passage par header en production._) ## Pour démarrer Lorsque vous disposez de votre token d'authentification, vous pouvez commencer à explorer notre API grâce au boutton  `Try it out` sur chacun de nos webs services. Mais au préalable, vous devez vous authentifier en cliquant sur le boutton `Authorize `, en remplissant l'input `api_key` avec `Bearer {{ JWT }}`.  **Exemple** `Bearer eyUEkiLCJh...CHCUiBfD63oxoo=` ## Limitation Toutes les requêtes à notre API sont loggées, c'est pourquoi vous devez respecter nos [CGU](https://dev.yanport.com/cgu) afin d'éviter tout usage abusif de notre API. 

    OpenAPI spec version: 1.0
    Contact: dev@yanport.com
    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""


from __future__ import absolute_import

import sys
import os
import re

# python 2 and python 3 compatibility library
from six import iteritems

from ..configuration import Configuration
from ..api_client import ApiClient


class AnnoncesApi(object):
    """
    NOTE: This class is auto generated by the swagger code generator program.
    Do not edit the class manually.
    Ref: https://github.com/swagger-api/swagger-codegen
    """

    def __init__(self, api_client=None):
        config = Configuration()
        if api_client:
            self.api_client = api_client
        else:
            if not config.api_client:
                config.api_client = ApiClient()
            self.api_client = config.api_client

    def ads_get(self, **kwargs):
        """
        Rechercher des annonces
        Recherche sur l'ensemble des annonces publiées par les portails selon certains critères comme la date de publication, le prix, la surface... _(voir ci-dessous pour une liste exhaustive)_.  La recherche plein-texte est disponible sur le titre et la description via le query param `q` _(voir notre [FAQ](https://yanporthelp.zendesk.com/hc/fr/articles/208456909-Comment-affiner-ma-recherche-avec-des-mots-cl%C3%A9s-) concernant la syntaxe)_  Par défaut les résultats sont paginés, pour parcourir l'ensemble des annonces les paramètres `from` et `size` doivent être renseignés. Le paramètre `from` définit le début du set de données et `size` le nombre d'éléments à récupérer. Le nombre `total` d'éléments est renvoyé dans la réponse.  Concernant le tri le paramètre `sort` à pour syntaxe `field:asc|desc` en remplaçant `field` par le nom du champ sur lequel appliqué le tri.  # Exemples   ## Les annonces en cours de publication sur Levallois-Perret entre 120 et 130m²     /ads?active=true&zipCodes=92300&surfaceMin=120&surfaceMax=130   ## Les annonces en cours de publication dans le 17ème arrondissement de Paris avec balcon     /ads?active=true&zipCodes=75017&q=balcon   ## Les dernières annonces de particulier publiées en Corse sur LeBonCoin et PAP     /ads?active=true&crawlSources=LE_BON_COIN&crawlSources=PAP&departments=2B&sort=property.marketing.publicationDate:asc 
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please define a `callback` function
        to be invoked when receiving the response.
        >>> def callback_function(response):
        >>>     pprint(response)
        >>>
        >>> thread = api.ads_get(callback=callback_function)

        :param callback function: The callback function
            for asynchronous request. (optional)
        :param int _from: Début de la pagination
        :param int size: Nombre de résultats
        :param str sort: Trier par
        :param str q: Recherche plein-texte
        :param list[str] marketing_types: Types de marché (vente, location, vente en viager)
        :param list[str] crawl_sources: Portails immobiliers
        :param bool active: Statut de l'annonce (expirée ou pas)
        :param list[str] dealer_types: Types de vendeur (agence, mandataire..)
        :param list[str] dealer_names: Liste de noms de vendeurs
        :param list[int] dealer_ids: Liste d'identifiants de vendeurs
        :param list[str] property_ids: Liste d'identifiants de biens
        :param list[str] property_types: Types de bien
        :param list[int] room_counts: Nombre de pièces
        :param list[str] departments: Liste de départements
        :param list[str] zip_codes: Liste de codes postaux
        :param list[int] city_ids: Liste d'identifiants de villes
        :param datetime publication_date_min: Date minimale de publication (YYYY-mm-ddTHH:mm:ss)
        :param datetime publication_date_max: Date limite de publication (YYYY-mm-ddTHH:mm:ss)
        :param datetime delete_date_min: Date minimale de suppression (YYYY-mm-ddTHH:mm:ss)
        :param datetime delete_date_max: Date limite de suppression (YYYY-mm-ddTHH:mm:ss)
        :param int duration_days_min: Durée minimale en jours
        :param int duration_days_max: Durée maximale en jours
        :param int surface_min: Surface minimale
        :param int surface_max: Surface maximale
        :param int price_min: Prix minimum
        :param int price_max: Prix maximum
        :param list[str] missing_fields: Attributs manquants
        :param list[str] existing_fields: Attributs existants
        :param list[str] excluded_ids: Identifiants à exclure
        :return: InlineResponse200
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('callback'):
            return self.ads_get_with_http_info(**kwargs)
        else:
            (data) = self.ads_get_with_http_info(**kwargs)
            return data

    def ads_get_with_http_info(self, **kwargs):
        """
        Rechercher des annonces
        Recherche sur l'ensemble des annonces publiées par les portails selon certains critères comme la date de publication, le prix, la surface... _(voir ci-dessous pour une liste exhaustive)_.  La recherche plein-texte est disponible sur le titre et la description via le query param `q` _(voir notre [FAQ](https://yanporthelp.zendesk.com/hc/fr/articles/208456909-Comment-affiner-ma-recherche-avec-des-mots-cl%C3%A9s-) concernant la syntaxe)_  Par défaut les résultats sont paginés, pour parcourir l'ensemble des annonces les paramètres `from` et `size` doivent être renseignés. Le paramètre `from` définit le début du set de données et `size` le nombre d'éléments à récupérer. Le nombre `total` d'éléments est renvoyé dans la réponse.  Concernant le tri le paramètre `sort` à pour syntaxe `field:asc|desc` en remplaçant `field` par le nom du champ sur lequel appliqué le tri.  # Exemples   ## Les annonces en cours de publication sur Levallois-Perret entre 120 et 130m²     /ads?active=true&zipCodes=92300&surfaceMin=120&surfaceMax=130   ## Les annonces en cours de publication dans le 17ème arrondissement de Paris avec balcon     /ads?active=true&zipCodes=75017&q=balcon   ## Les dernières annonces de particulier publiées en Corse sur LeBonCoin et PAP     /ads?active=true&crawlSources=LE_BON_COIN&crawlSources=PAP&departments=2B&sort=property.marketing.publicationDate:asc 
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please define a `callback` function
        to be invoked when receiving the response.
        >>> def callback_function(response):
        >>>     pprint(response)
        >>>
        >>> thread = api.ads_get_with_http_info(callback=callback_function)

        :param callback function: The callback function
            for asynchronous request. (optional)
        :param int _from: Début de la pagination
        :param int size: Nombre de résultats
        :param str sort: Trier par
        :param str q: Recherche plein-texte
        :param list[str] marketing_types: Types de marché (vente, location, vente en viager)
        :param list[str] crawl_sources: Portails immobiliers
        :param bool active: Statut de l'annonce (expirée ou pas)
        :param list[str] dealer_types: Types de vendeur (agence, mandataire..)
        :param list[str] dealer_names: Liste de noms de vendeurs
        :param list[int] dealer_ids: Liste d'identifiants de vendeurs
        :param list[str] property_ids: Liste d'identifiants de biens
        :param list[str] property_types: Types de bien
        :param list[int] room_counts: Nombre de pièces
        :param list[str] departments: Liste de départements
        :param list[str] zip_codes: Liste de codes postaux
        :param list[int] city_ids: Liste d'identifiants de villes
        :param datetime publication_date_min: Date minimale de publication (YYYY-mm-ddTHH:mm:ss)
        :param datetime publication_date_max: Date limite de publication (YYYY-mm-ddTHH:mm:ss)
        :param datetime delete_date_min: Date minimale de suppression (YYYY-mm-ddTHH:mm:ss)
        :param datetime delete_date_max: Date limite de suppression (YYYY-mm-ddTHH:mm:ss)
        :param int duration_days_min: Durée minimale en jours
        :param int duration_days_max: Durée maximale en jours
        :param int surface_min: Surface minimale
        :param int surface_max: Surface maximale
        :param int price_min: Prix minimum
        :param int price_max: Prix maximum
        :param list[str] missing_fields: Attributs manquants
        :param list[str] existing_fields: Attributs existants
        :param list[str] excluded_ids: Identifiants à exclure
        :return: InlineResponse200
                 If the method is called asynchronously,
                 returns the request thread.
        """

        all_params = ['_from', 'size', 'sort', 'q', 'marketing_types', 'crawl_sources', 'active', 'dealer_types', 'dealer_names', 'dealer_ids', 'property_ids', 'property_types', 'room_counts', 'departments', 'zip_codes', 'city_ids', 'publication_date_min', 'publication_date_max', 'delete_date_min', 'delete_date_max', 'duration_days_min', 'duration_days_max', 'surface_min', 'surface_max', 'price_min', 'price_max', 'missing_fields', 'existing_fields', 'excluded_ids']
        all_params.append('callback')
        all_params.append('_return_http_data_only')
        all_params.append('_preload_content')
        all_params.append('_request_timeout')

        params = locals()
        for key, val in iteritems(params['kwargs']):
            if key not in all_params:
                raise TypeError(
                    "Got an unexpected keyword argument '%s'"
                    " to method ads_get" % key
                )
            params[key] = val
        del params['kwargs']

        if '_from' in params and params['_from'] < 0:
            raise ValueError("Invalid value for parameter `_from` when calling `ads_get`, must be a value greater than or equal to `0`")
        if 'size' in params and params['size'] > 1000:
            raise ValueError("Invalid value for parameter `size` when calling `ads_get`, must be a value less than or equal to `1000`")
        if 'size' in params and params['size'] < 0:
            raise ValueError("Invalid value for parameter `size` when calling `ads_get`, must be a value greater than or equal to `0`")

        collection_formats = {}

        path_params = {}

        query_params = []
        if '_from' in params:
            query_params.append(('from', params['_from']))
        if 'size' in params:
            query_params.append(('size', params['size']))
        if 'sort' in params:
            query_params.append(('sort', params['sort']))
        if 'q' in params:
            query_params.append(('q', params['q']))
        if 'marketing_types' in params:
            query_params.append(('marketingTypes', params['marketing_types']))
            collection_formats['marketingTypes'] = 'multi'
        if 'crawl_sources' in params:
            query_params.append(('crawlSources', params['crawl_sources']))
            collection_formats['crawlSources'] = 'multi'
        if 'active' in params:
            query_params.append(('active', params['active']))
        if 'dealer_types' in params:
            query_params.append(('dealerTypes', params['dealer_types']))
            collection_formats['dealerTypes'] = 'multi'
        if 'dealer_names' in params:
            query_params.append(('dealerNames', params['dealer_names']))
            collection_formats['dealerNames'] = 'multi'
        if 'dealer_ids' in params:
            query_params.append(('dealerIds', params['dealer_ids']))
            collection_formats['dealerIds'] = 'multi'
        if 'property_ids' in params:
            query_params.append(('propertyIds', params['property_ids']))
            collection_formats['propertyIds'] = 'multi'
        if 'property_types' in params:
            query_params.append(('propertyTypes', params['property_types']))
            collection_formats['propertyTypes'] = 'multi'
        if 'room_counts' in params:
            query_params.append(('roomCounts', params['room_counts']))
            collection_formats['roomCounts'] = 'multi'
        if 'departments' in params:
            query_params.append(('departments', params['departments']))
            collection_formats['departments'] = 'multi'
        if 'zip_codes' in params:
            query_params.append(('zipCodes', params['zip_codes']))
            collection_formats['zipCodes'] = 'multi'
        if 'city_ids' in params:
            query_params.append(('cityIds', params['city_ids']))
            collection_formats['cityIds'] = 'multi'
        if 'publication_date_min' in params:
            query_params.append(('publicationDateMin', params['publication_date_min']))
        if 'publication_date_max' in params:
            query_params.append(('publicationDateMax', params['publication_date_max']))
        if 'delete_date_min' in params:
            query_params.append(('deleteDateMin', params['delete_date_min']))
        if 'delete_date_max' in params:
            query_params.append(('deleteDateMax', params['delete_date_max']))
        if 'duration_days_min' in params:
            query_params.append(('durationDaysMin', params['duration_days_min']))
        if 'duration_days_max' in params:
            query_params.append(('durationDaysMax', params['duration_days_max']))
        if 'surface_min' in params:
            query_params.append(('surfaceMin', params['surface_min']))
        if 'surface_max' in params:
            query_params.append(('surfaceMax', params['surface_max']))
        if 'price_min' in params:
            query_params.append(('priceMin', params['price_min']))
        if 'price_max' in params:
            query_params.append(('priceMax', params['price_max']))
        if 'missing_fields' in params:
            query_params.append(('missingFields', params['missing_fields']))
            collection_formats['missingFields'] = 'csv'
        if 'existing_fields' in params:
            query_params.append(('existingFields', params['existing_fields']))
            collection_formats['existingFields'] = 'csv'
        if 'excluded_ids' in params:
            query_params.append(('excludedIds', params['excluded_ids']))
            collection_formats['excludedIds'] = 'csv'

        header_params = {}

        form_params = []
        local_var_files = {}

        body_params = None
        # HTTP header `Accept`
        header_params['Accept'] = self.api_client.\
            select_header_accept(['application/json'])

        # Authentication setting
        auth_settings = ['jwt']

        return self.api_client.call_api('/ads', 'GET',
                                        path_params,
                                        query_params,
                                        header_params,
                                        body=body_params,
                                        post_params=form_params,
                                        files=local_var_files,
                                        response_type='InlineResponse200',
                                        auth_settings=auth_settings,
                                        callback=params.get('callback'),
                                        _return_http_data_only=params.get('_return_http_data_only'),
                                        _preload_content=params.get('_preload_content', True),
                                        _request_timeout=params.get('_request_timeout'),
                                        collection_formats=collection_formats)

    def ads_id_get(self, id, **kwargs):
        """
        Récupérer une annonce (ID)
        Récupérer une annonce par son identifiant
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please define a `callback` function
        to be invoked when receiving the response.
        >>> def callback_function(response):
        >>>     pprint(response)
        >>>
        >>> thread = api.ads_id_get(id, callback=callback_function)

        :param callback function: The callback function
            for asynchronous request. (optional)
        :param str id: L'identifiant de l'annonce (required)
        :return: Ad
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('callback'):
            return self.ads_id_get_with_http_info(id, **kwargs)
        else:
            (data) = self.ads_id_get_with_http_info(id, **kwargs)
            return data

    def ads_id_get_with_http_info(self, id, **kwargs):
        """
        Récupérer une annonce (ID)
        Récupérer une annonce par son identifiant
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please define a `callback` function
        to be invoked when receiving the response.
        >>> def callback_function(response):
        >>>     pprint(response)
        >>>
        >>> thread = api.ads_id_get_with_http_info(id, callback=callback_function)

        :param callback function: The callback function
            for asynchronous request. (optional)
        :param str id: L'identifiant de l'annonce (required)
        :return: Ad
                 If the method is called asynchronously,
                 returns the request thread.
        """

        all_params = ['id']
        all_params.append('callback')
        all_params.append('_return_http_data_only')
        all_params.append('_preload_content')
        all_params.append('_request_timeout')

        params = locals()
        for key, val in iteritems(params['kwargs']):
            if key not in all_params:
                raise TypeError(
                    "Got an unexpected keyword argument '%s'"
                    " to method ads_id_get" % key
                )
            params[key] = val
        del params['kwargs']
        # verify the required parameter 'id' is set
        if ('id' not in params) or (params['id'] is None):
            raise ValueError("Missing the required parameter `id` when calling `ads_id_get`")


        collection_formats = {}

        path_params = {}
        if 'id' in params:
            path_params['id'] = params['id']

        query_params = []

        header_params = {}

        form_params = []
        local_var_files = {}

        body_params = None
        # HTTP header `Accept`
        header_params['Accept'] = self.api_client.\
            select_header_accept(['application/json'])

        # Authentication setting
        auth_settings = ['jwt']

        return self.api_client.call_api('/ads/{id}', 'GET',
                                        path_params,
                                        query_params,
                                        header_params,
                                        body=body_params,
                                        post_params=form_params,
                                        files=local_var_files,
                                        response_type='Ad',
                                        auth_settings=auth_settings,
                                        callback=params.get('callback'),
                                        _return_http_data_only=params.get('_return_http_data_only'),
                                        _preload_content=params.get('_preload_content', True),
                                        _request_timeout=params.get('_request_timeout'),
                                        collection_formats=collection_formats)

    def ads_ids_get(self, ids, **kwargs):
        """
        Récupérer des annonces (ID)
        Récupérer des annonces par leurs identifiants
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please define a `callback` function
        to be invoked when receiving the response.
        >>> def callback_function(response):
        >>>     pprint(response)
        >>>
        >>> thread = api.ads_ids_get(ids, callback=callback_function)

        :param callback function: The callback function
            for asynchronous request. (optional)
        :param list[str] ids: Les identifiants des annonces (required)
        :return: list[Ad]
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('callback'):
            return self.ads_ids_get_with_http_info(ids, **kwargs)
        else:
            (data) = self.ads_ids_get_with_http_info(ids, **kwargs)
            return data

    def ads_ids_get_with_http_info(self, ids, **kwargs):
        """
        Récupérer des annonces (ID)
        Récupérer des annonces par leurs identifiants
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please define a `callback` function
        to be invoked when receiving the response.
        >>> def callback_function(response):
        >>>     pprint(response)
        >>>
        >>> thread = api.ads_ids_get_with_http_info(ids, callback=callback_function)

        :param callback function: The callback function
            for asynchronous request. (optional)
        :param list[str] ids: Les identifiants des annonces (required)
        :return: list[Ad]
                 If the method is called asynchronously,
                 returns the request thread.
        """

        all_params = ['ids']
        all_params.append('callback')
        all_params.append('_return_http_data_only')
        all_params.append('_preload_content')
        all_params.append('_request_timeout')

        params = locals()
        for key, val in iteritems(params['kwargs']):
            if key not in all_params:
                raise TypeError(
                    "Got an unexpected keyword argument '%s'"
                    " to method ads_ids_get" % key
                )
            params[key] = val
        del params['kwargs']
        # verify the required parameter 'ids' is set
        if ('ids' not in params) or (params['ids'] is None):
            raise ValueError("Missing the required parameter `ids` when calling `ads_ids_get`")


        collection_formats = {}

        path_params = {}

        query_params = []
        if 'ids' in params:
            query_params.append(('ids', params['ids']))
            collection_formats['ids'] = 'multi'

        header_params = {}

        form_params = []
        local_var_files = {}

        body_params = None
        # HTTP header `Accept`
        header_params['Accept'] = self.api_client.\
            select_header_accept(['application/json'])

        # Authentication setting
        auth_settings = ['jwt']

        return self.api_client.call_api('/ads/ids', 'GET',
                                        path_params,
                                        query_params,
                                        header_params,
                                        body=body_params,
                                        post_params=form_params,
                                        files=local_var_files,
                                        response_type='list[Ad]',
                                        auth_settings=auth_settings,
                                        callback=params.get('callback'),
                                        _return_http_data_only=params.get('_return_http_data_only'),
                                        _preload_content=params.get('_preload_content', True),
                                        _request_timeout=params.get('_request_timeout'),
                                        collection_formats=collection_formats)

    def ads_urls_get(self, url, **kwargs):
        """
        Récupérer une annonce (URL)
        Récupérer une annonce par son url
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please define a `callback` function
        to be invoked when receiving the response.
        >>> def callback_function(response):
        >>>     pprint(response)
        >>>
        >>> thread = api.ads_urls_get(url, callback=callback_function)

        :param callback function: The callback function
            for asynchronous request. (optional)
        :param str url: Url de l'annonce (required)
        :return: Ad
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('callback'):
            return self.ads_urls_get_with_http_info(url, **kwargs)
        else:
            (data) = self.ads_urls_get_with_http_info(url, **kwargs)
            return data

    def ads_urls_get_with_http_info(self, url, **kwargs):
        """
        Récupérer une annonce (URL)
        Récupérer une annonce par son url
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please define a `callback` function
        to be invoked when receiving the response.
        >>> def callback_function(response):
        >>>     pprint(response)
        >>>
        >>> thread = api.ads_urls_get_with_http_info(url, callback=callback_function)

        :param callback function: The callback function
            for asynchronous request. (optional)
        :param str url: Url de l'annonce (required)
        :return: Ad
                 If the method is called asynchronously,
                 returns the request thread.
        """

        all_params = ['url']
        all_params.append('callback')
        all_params.append('_return_http_data_only')
        all_params.append('_preload_content')
        all_params.append('_request_timeout')

        params = locals()
        for key, val in iteritems(params['kwargs']):
            if key not in all_params:
                raise TypeError(
                    "Got an unexpected keyword argument '%s'"
                    " to method ads_urls_get" % key
                )
            params[key] = val
        del params['kwargs']
        # verify the required parameter 'url' is set
        if ('url' not in params) or (params['url'] is None):
            raise ValueError("Missing the required parameter `url` when calling `ads_urls_get`")


        collection_formats = {}

        path_params = {}

        query_params = []
        if 'url' in params:
            query_params.append(('url', params['url']))

        header_params = {}

        form_params = []
        local_var_files = {}

        body_params = None
        # HTTP header `Accept`
        header_params['Accept'] = self.api_client.\
            select_header_accept(['application/json'])

        # Authentication setting
        auth_settings = ['jwt']

        return self.api_client.call_api('/ads/urls', 'GET',
                                        path_params,
                                        query_params,
                                        header_params,
                                        body=body_params,
                                        post_params=form_params,
                                        files=local_var_files,
                                        response_type='Ad',
                                        auth_settings=auth_settings,
                                        callback=params.get('callback'),
                                        _return_http_data_only=params.get('_return_http_data_only'),
                                        _preload_content=params.get('_preload_content', True),
                                        _request_timeout=params.get('_request_timeout'),
                                        collection_formats=collection_formats)
