# scripts/delete_all_questions.py
# *coding: utf-8*

from backoffice.models import Place
import requests
import urllib
import time
import logging,json
logger = logging.getLogger('django')

def run():
    # Fetch all places
    allPlaces = Place.objects.filter(valid=True)
    import tempfile

    from django.core import files
    for place in allPlaces:
        if place.googlePlaceId:
            url="https://maps.googleapis.com/maps/api/place/details/json?place_id="+place.googlePlaceId+"&key=AIzaSyC2StTKAdCeCl2zUwzNhLxR8kWWyqOQjYQ"
            try:
                print("On doit checker " + url)
                response = requests.get(url)
                data = response.json()
                if data["status"] == "OK":
                    place.googlePlaceJson=json.dumps(data["result"])
                    result = data["result"]

                    if "photos" in result:
                        print("Photos %s"%result["photos"])
                        first = result["photos"][0]
                        reference = first["photo_reference"]
                        #get info
                        urlPhoto="https://maps.googleapis.com/maps/api/place/photo?key=AIzaSyC2StTKAdCeCl2zUwzNhLxR8kWWyqOQjYQ&maxwidth=400&photoreference="+reference
                        try:
                            response = requests.get(urlPhoto, stream=True)
                            if response.status_code != requests.codes.ok:
                                # Nope, error handling, skip file etc etc etc
                                continue

                            # Get the filename from the url, used for saving later
                            file_name = reference

                            # Create a temporary file
                            lf = tempfile.NamedTemporaryFile()

                            # Read the streamed image in sections
                            for block in response.iter_content(1024 * 8):

                                # If no more file then stop
                                if not block:
                                    break

                                # Write image block to temporary file
                                lf.write(block)

                            # Save the temporary image to the model#
                            # This saves the model so be sure that is it valid
                            place.mainPhoto.save(file_name, files.File(lf))
                            print("enregistre photo")
                        except Exception as e:
                            print(e)

                    place.save()
            except Exception as e:
                print(e)





