## Helper file to geocode address using Google Geocoder
# *coding: utf-8*

import urllib, urllib2, simplejson
from django.utils.encoding import smart_str
import logging,os
from django.core.files.storage import default_storage
from django.db.models import FileField

# Get an instance of a logger
logger = logging.getLogger('django')


def delete_files(files_list):
    for file_ in files_list:
        if file_ and hasattr(file_, 'storage') and hasattr(file_, 'path'):
            # this accounts for different file storages (e.g. when using django-storages)
            #DELETE FILES On efface le fichier /home/csurbier/Documents/Programmation/agenderbackend/static/storage/media/avatar.png
            storage_, path_ = file_.storage, file_.path
            if "avatar.png" not in path_:
                storage_.delete(path_)
                logger.info("DELETE FILES On efface le fichier %s" % path_)

def file_cleanup(sender, **kwargs):
    """
    File cleanup callback used to emulate the old delete
    behavior using signals. Initially django deleted linked
    files when an object containing a File/ImageField was deleted.

    Usage:
    >>> from django.db.models.signals import post_delete
    >>> post_delete.connect(file_cleanup, sender=MyModel, dispatch_uid="mymodel.file_cleanup")
    """
    logger.info("============== DOIT EFFACER")

    for fieldname in sender._meta.get_fields():
        try:
            logger.info("On essaye le field de nom %s" % (fieldname))
            field = sender._meta.get_field(fieldname)
        except:
            logger.info("ERREUR get fields")
            field = None
        if field and isinstance(field, FileField):
            inst = kwargs['instance']
            f = getattr(inst, fieldname)
            m = inst.__class__._default_manager
            if hasattr(f, 'path') and os.path.exists(f.path)\
            and not m.filter(**{'%s__exact' % fieldname: getattr(inst, fieldname)})\
            .exclude(pk=inst._get_pk_val()):
                try:
                    default_storage.delete(f.path)
                    logger.info("On efface le fichier %s" % f.path)
                except:
                    logger.info("ERREUR DELETE fichier %s" % f.path)
                    pass


def get_lng_lat(location):
    # Reference: http://djangosnippets.org/snippets/293/

    location = urllib.quote_plus(smart_str(location))
    url = 'https://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false&key=AIzaSyC_JT9okK3ND5r3yzXuGuBUeBsRq8MO8Ow' % location
    response = urllib2.urlopen(url).read()
    result = simplejson.loads(response)
    if result['status'] == 'OK':
        locationFound = result['results'][0]['geometry']['location']
        return locationFound
    else:
        return ''