U
    dKN                     @   s  d dl Z d dlZd dlmZ d dlmZ d dlmZmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZ d dlmZ d dlmZ d dlmZmZ d dlmZmZ d d	lmZ d
dl m!Z! erd dl"m#Z# z,d dl$Z$e$% Z&ee'e'f edddZ(W n6 e)k
r&   d dl*Z*ee'e'f edddZ(Y nX e Z+G dd deZ,edd Z-G dd deZ.ede.f Z/ee'e0df Z1G dd deZ2G dd deZ3G dd de!Z4e4 Z5dS )    N)contextmanager)NullTranslations)TYPE_CHECKINGAnyCallableDictIterableList
NamedTupleOptionalSetTupleUnioncastoverload)Local)	force_str)override
trans_real)Literal	TypedDict)settings   )CountriesBase)
StrPromise)itemreturnc                 C   s   t | d S Nr   )collatorsort_keyr    r!   =/tmp/pip-unpacked-wheel-dnjn05s9/django_countries/__init__.pyr   (   s    r   c                 C   s   t d| d dddS )NZNFKDr   asciiignore)unicodedata	normalizeencodedecoder    r!   r!   r"   r   0   s     c                       s$   e Zd Zeed fddZ  ZS )EmptyFallbackTranslator)messager   c                    s   t tddsdS t |S )NfallbackT )getattr_translation_statesupergettext)selfr*   	__class__r!   r"   r0   <   s    zEmptyFallbackTranslator.gettext)__name__
__module____qualname__strr0   __classcell__r!   r!   r2   r"   r)   ;   s   r)   c                  c   sX   t jsd V  d S t } | j}t|ts:t }||_|| _dt_z
d V  W 5 dt_X d S )NFT)	r   ZUSE_I18Nr   catalog	_fallback
isinstancer)   r.   r+   )r9   Zoriginal_fallbackZempty_fallback_translatorr!   r!   r"   no_translation_fallbackC   s    

r<   c                   @   s6   e Zd ZU ded< ded< eed< eed< eed< dS )	ComplexCountryNamer   namezList[StrPromise]namesalpha3numericioc_codeN)r4   r5   r6   __annotations__r7   intr!   r!   r!   r"   r=   W   s
   
r=   r   c                   @   s"   e Zd ZU eed< ee ed< dS )AltCodesr@   rA   N)r4   r5   r6   r7   rC   r   rD   r!   r!   r!   r"   rE   c   s   
rE   c                   @   s,   e Zd ZU eed< eed< edddZdS )CountryTuplecoder>   r   c                 C   s   d| j d| jdS )z
        Display the repr as a standard tuple for better backwards
        compatibility with outputting this in a template.
        (z, )rG   r>   r1   r!   r!   r"   __repr__l   s    zCountryTuple.__repr__N)r4   r5   r6   r7   rC   rM   r!   r!   r!   r"   rF   h   s   
rF   c                	   @   s,  e Zd ZU dZeeef ed< eeef ed< edddZ	e
eeef ddd	Zejd
d	 Ze
eeef dddZe
eeef dddZe
dd Zd;eeee  dddZd<eee dddZdd ZeedddZeedddZedd d!d"eed eeed#d$d%Zed d!d&eed! eeee d#d'd%Zdd d!d"eeeeeeee f d#d(d%Zeedd)d*Zed=eeedf ed ee d+d,d-Z eeeedf ed! ee d+d.d-Z d>eeedf ed/d0d-Z eedd1d2Z!d3d4 Z"d5d6 Z#d7d8 Z$d9d: Z%dS )?	Countriesz
    An object containing a list of ISO3166-1 countries.

    Iterating this object will return the countries as namedtuples (of
    the country ``code`` and ``name``), sorted by name.
    
_countries
_alt_codes)optionc                 C   s,   t | |d}|dk	r|S t td|  S )z
        Get a configuration option, trying the options attribute first and
        falling back to a Django project setting.
        NZ
COUNTRIES_)r-   r   upper)r1   rQ   valuer!   r!   r"   
get_option   s    zCountries.get_optionrH   c                 C   s  t | ds| d}d}|rDt|tsD|D ]}t|tr,d} qDq,i | _|r`|r`t|| _ndddlm} t|}|ri | _|D ]0}t|tr|| | j|< q|\}}|| j|< qn
|	 | _| dr| j
 D ]\}}	|| jkr|	| j|< q| d}
|
r@tttttd	f f | j	 }||
 d
d | D | _| dr| j
D ],}|| jkrR||
krR|| g| j|< qR| j D ]8\}}|| jkr||
kr| j|g }|| qg | _| dpg }|D ](}| |}|| jkr| j| q| jS )z
        Return the a dictionary of countries, modified by any overriding
        options.

        The result is cached so future lookups are less work intensive.
        rO   onlyTFr   )	COUNTRIESZcommon_namesr   Nc                 S   s   i | ]\}}|d k	r||qS Nr!   ).0rG   r>   r!   r!   r"   
<dictcomp>   s    z'Countries.countries.<locals>.<dictcomp>first)hasattrrT   r;   dictr7   _shadowed_namesrO   django_countries.datarV   copyZCOMMON_NAMESitemsr   r   r   CountryNameupdateZ	OLD_NAMES
setdefaultextendcountries_firstalpha2append)r1   rU   Zonly_choicesr   rV   Zcountries_dictkeyrS   rG   r>   r   rO   r?   Zcountry_shadowedrZ   r!   r!   r"   	countries   sn    





 


zCountries.countriesc                 C   s<   t | dr| `t | dr| `t | dr*| `t | dr8| `dS )z
        Reset the countries cache in case for some crazy reason the settings or
        internal options change. But surely no one is crazy enough to do that,
        right?
        rO   rP   
_ioc_codesr]   N)r[   rO   rP   rj   r]   rL   r!   r!   r"   ri      s    



c                 C   s   t | dsddlm} || _d}| j D ]x\}}t|tr*d|ksLd|kr*|s`| j | _d}| j	|d\}}d|kr|d }d|kr|d }t
||| j|< q*| jS )	NrP   r   )	ALT_CODESFr@   rA   T)r,   N)r[   r^   rk   rP   ri   r`   r;   r\   r_   getrE   )r1   rk   alteredrG   countryr@   rA   r!   r!   r"   	alt_codes   s(    

zCountries.alt_codesc                 C   sn   t | dshddlm} || _d}| j D ]<\}}t|tr*d|kr*|sX| j | _d}|d | j|< q*| jS )Nrj   r   )
ISO_TO_IOCFrB   T)	r[   Zdjango_countries.ioc_datarp   rj   ri   r`   r;   r\   r_   )r1   rp   rm   rG   rn   r!   r!   r"   	ioc_codes   s    
zCountries.ioc_codesc                 C   s   t | dds| j | jS )Nr]   F)r-   ri   r]   rL   r!   r!   r"   shadowed_names	  s    zCountries.shadowed_namesN)rG   ignore_firstc                 c   sl   | j | }t|tr2d|kr&|d }q8|d g}n|g}|rP||krP|dd }|D ]}| ||V  qTdS )zA
        Return translated countries for a country code.
        r?   r>   r   N)ri   r;   r\   translate_pair)r1   rG   rs   rn   r?   r>   r!   r!   r"   translate_code  s    


zCountries.translate_coderK   c              	   C   s   |dkr| j | }t|trPd|krB|d dd }|d d }q^g }|d }n| j|g }|rt 0 t|}|s|D ]}t|}|rz|} qqzW 5 Q R X |st|}nt|}t||S )z
        Force a country to the current activated translation.

        :returns: ``CountryTuple(code, translated_country_name)`` namedtuple
        Nr?   r   r   r>   )ri   r;   r\   rr   rl   r<   r   rF   )r1   rG   r>   Zfallback_namesZcountry_nameZfallback_nameZfallback_name_strr!   r!   r"   rt   !  s,    



zCountries.translate_pairc                 #   s   j }fddjD }dr0t|td}|E dH  jr^d}|r^tdt|V  drldnj ttj	
 fd	d|D }t|tdE dH  dS )
a  
        Iterate through countries, sorted by name.

        Each country record consists of a namedtuple of the two letter
        ISO3166-1 country ``code`` and short ``name``.

        The sorting happens based on the thread's current translation.

        Countries that are in ``settings.COUNTRIES_FIRST`` will be
        displayed before any sorted countries (in the order provided),
        and are only repeated in the sorted list if
        ``settings.COUNTRIES_FIRST_REPEAT`` is ``True``.

        The first countries can be separated from the sorted list by the
        value provided in ``settings.COUNTRIES_FIRST_BREAK``.
        c                 3   s   | ]}  |V  qd S rW   )rt   rX   rG   rL   r!   r"   	<genexpr>Y  s     z%Countries.__iter__.<locals>.<genexpr>Z
first_sort)rh   Nfirst_breakr,   Zfirst_repeatc                 3   s   | ]} | V  qd S rW   )ru   rv   rs   r1   r!   r"   rw   h  s    )ri   re   rT   sortedr   rF   r   tuple	itertoolschainfrom_iterable)r1   ri   re   rx   r!   ry   r"   __iter__D  s     


zCountries.__iter__)rG   r   c                    s   t | }| r*t|fdd}n(t|dkrN| td fdd}nd}|r~d}| j D ]\}}||rd|} q~qd|| jkr|S dS )af  
        Return the normalized country code when passed any type of ISO 3166-1
        country code.

        Overridden countries objects may actually have country codes that are
        not two characters (for example, "GB-WLS"), so the returned length of
        the code is not guaranteed.

        If no match is found, returns an empty string.
        c                    s   | d  kS r   r!   ro   )lookup_numericr!   r"   find  s    zCountries.alpha2.<locals>.find   rH   c                    s   | d  kS )Nr   r!   r   )lookup_alpha3r!   r"   r     s    Nr,   )	r   rR   isdigitrD   lenboolro   r`   ri   )r1   rG   Zcode_strr   rf   ro   r!   )r   r   r"   rf   p  s"    
zCountries.alpha2c                 C   s&   |  |}|| jkrdS | |d S )zz
        Return the name of a country, based on the code.

        If no match is found, returns an empty string.
        r,   r   )rf   ri   rt   r1   rG   rf   r!   r!   r"   r>     s    

zCountries.nameFenT)regexlanguageinsensitive)rn   r   r   r   r   c                C   s   d S rW   r!   r1   rn   r   r   r   r!   r!   r"   by_name  s    	zCountries.by_name)r   r   c                C   s   d S rW   r!   r   r!   r!   r"   r     s    	c             
   C   sr  t  }|rt||otj}n|r*| }t|* | j D ]\}}t|t	rrd|krf|d }	qx|d g}	n|g}	|	D ]l}
|r|
t|
r|| q||r||
 kr|    W  5 Q R  S q|||
kr||    W  5 Q R  S q||| jkr@| j| D ]X}|r$|
t|rT|| n0|r2| }||k r|    W  5 Q R  S  qq@W 5 Q R X |rn|S dS )a	  
        Fetch a country's ISO3166-1 two letter country code from its name.

        An optional language parameter is also available. Warning: This depends
        on the quality of the available translations.

        If no match is found, returns an empty string.

        If ``regex`` is set to True, then rather than returning a string
        containing the matching country code or an empty string, a set of
        matching country codes is returned.

        If ``insensitive`` is set to False (True by default), then the search
        will be case sensitive.

        ..warning:: Be cautious about relying on this returning a country code
            (especially with any hard-coded string) since the ISO names of
            countries may change over time.
        r?   r>   r,   )setrecompile
IGNORECASElowerr   ri   r`   r;   r\   searchr7   addrr   )r1   rn   r   r   r   Z	code_listre_matchrG   Zcheck_countryZcheck_namesr>   Zshadowed_namer!   r!   r"   r     sB    



(c                 C   s>   |  |}z| j| d }W n tk
r4   d}Y nX |p<dS )z
        Return the ISO 3166-1 three letter country code matching the provided
        country code.

        If no match is found, returns an empty string.
        r   r,   rf   ro   KeyError)r1   rG   rf   r@   r!   r!   r"   r@     s    

zCountries.alpha3)rG   paddedr   c                 C   s   d S rW   r!   r1   rG   r   r!   r!   r"   rA     s    zCountries.numericc                 C   s   d S rW   r!   r   r!   r!   r"   rA     s    )rG   r   c                 C   sR   |  |}z| j| d }W n tk
r4   d}Y nX |dkrBdS |rNd| S |S )a  
        Return the ISO 3166-1 numeric country code matching the provided
        country code.

        If no match is found, returns ``None``.

        :param padded: Pass ``True`` to return a 0-padded three character
            string, otherwise an integer will be returned.
        r   Nz%03dr   )r1   rG   r   rf   numr!   r!   r"   rA     s    


c                 C   s   |  |}| j|dS )z
        Return the International Olympic Committee three letter code matching
        the provided ISO 3166-1 country code.

        If no match is found, returns an empty string.
        r,   )rf   rq   rl   r   r!   r!   r"   rB   '  s    
zCountries.ioc_codec                 C   s4   t | j}|t | j7 }| jr0| dr0|d7 }|S )z
        len() used by several third party applications to calculate the length
        of choices. This will solve a bug related to generating fixtures.
        rx   r   )r   ri   re   rT   )r1   countr!   r!   r"   __len__1  s
    
zCountries.__len__c                 C   s
   t | jS rW   )r   ri   rL   r!   r!   r"   __bool__=  s    zCountries.__bool__c                 C   s
   || j kS )zH
        Check to see if the countries contains the given code.
        )ri   )r1   rG   r!   r!   r"   __contains__@  s    zCountries.__contains__c              
   C   sT   zt t|  ||d W S  tk
rN   tt|  |j|j|j Y S X dS )zn
        Some applications expect to be able to access members of the field
        choices by index.
        r   N)	nextr|   islicer   	TypeErrorliststartstopstep)r1   indexr!   r!   r"   __getitem__F  s    zCountries.__getitem__)N)N)F)F)&r4   r5   r6   __doc__r   r7   ra   rC   rE   rT   propertyri   deleterro   rq   rr   r   r	   ru   rt   r   CountryCoderf   r>   r   r   r   r   r   r   r@   rD   rA   rB   r   r   r   r   r!   r!   r!   r"   rN   t   s   

I

#,%
B   
rN   )6r|   r   
contextlibr   r0   r   typingr   r   r   r   r   r	   r
   r   r   r   r   r   r   Zasgiref.localr   Zdjango.utils.encodingr   Zdjango.utils.translationr   r   Ztyping_extensionsr   r   Zdjango_countries.confr   baser   Zdjango_stubs_extr   ZpyucaZCollatorr   r7   r   ImportErrorr%   r.   r)   r<   r=   ra   rD   r   rE   rF   rN   ri   r!   r!   r!   r"   <module>   sB   <
   b