from django.core.management.base import BaseCommand
from optparse import make_option
from datetime import datetime

from stories.models import Story, Location
from people.models import Author

import codecs
import json
import requests
from unidecode import unidecode

class Command(BaseCommand):
    args = '<filename> --flush'
    help = """Import a JSON of stories from the OurWalmart"""
    option_list = BaseCommand.option_list + (
        make_option('--flush',
                    action='store_true',
                    dest='flush',
                    default=False,
                    help='Delete all stories before importing walmart stories'),
        )

    def handle(self, *args, **options):
        if options['flush']:
            old = Story.objects.filter(employer__startswith="Walmart")
            confirm = raw_input('This will delete all %d existing Walmart stories. Are you sure? [y/N] ' % old.count())
            if confirm == 'y':
                old.delete()

        with codecs.open('stories/fixtures/walmart-faces.json', 'r', encoding='utf-8') as jsonfile:
            stories = json.load(jsonfile)

            n_s, n_a, n_l = (0, 0, 0)
            for data in stories:
                try:
                    story, new_story = Story.objects.get_or_create(content=data.get('story'))
                except Story.MultipleObjectsReturned:
                    duplicates = Story.objects.filter(content=data.get('story'))
                    duplicates.delete()

                    story = Story(content=data.get('story'))

                first_name = unidecode(data.get('fname'))
                last_name = unidecode(data.get('lname'))

                author, new_author = Author.objects.get_or_create_user(first_name=first_name, last_name=last_name)
                if new_author:
                    n_a = n_a+1

                    if data.get('email'):
                        author.user.email = data.get('email')

                    author.user.active = False
                    author.user.save()

                    if data.get('store'):
                        author.employer = "Walmart #"+data.get('store')
                    else:
                        author.employer = "Walmart"

                    if data.get('associate'):
                        author.occupation = "Associate"

                    if data.get('anonymous'):
                        author.anonymous = True

                    author.save()

                story.author = author

                if data.get('zip'):
                    zipcode = data.get('zip')

                    # do zip -> city lookup inline
                    zip_lookup = requests.get("http://api.zippopotam.us/us/"+zipcode)
                    print "lookup", zipcode
                    place = zip_lookup.json().get('places', [{}])[0]

                    location, new_location = Location.objects.get_or_create(city__iexact=place.get('place name'), state=place.get('state abbreviation'))
                    if new_location and place.get('latitude') and place.get('longitude'):
                        location.city = place.get('place name')
                        location.state = place.get('state abbreviation')
                        location.lat = place.get('latitude')
                        location.lon = place.get('longitude')
                        location.geocoded = True
                        location.save()

                        n_l = n_l+1

                    story.location = location
                story.save()

                # export date from OurWalmart
                story.created_at = datetime(2013, 9, 4, 0, 0)
                story.updated_at = datetime.now()

                story.save()

                if new_story:
                    n_s = n_s+1

            self.stdout.write("imported %d stories by %d authors in %d locations" % (n_s, n_a, n_l))

@@ -2839,449 +2839,1350 @@
 %5B0%5D%0A
-%0A                    location, new_location = Location.objects.get_or_create(city__iexact=place.get('place name'), state=place.get('state abbreviation'))%0A                    if new_location and place.get('latitude') and place.get('longitude'):%0A                        location.city = place.get('place name')%0A                        location.state = place.get('state abbreviation')%0A                        location.lat = place.get('latitude')
+                    city = place.get('place name')%0A                    state = place.get('state abbreviation')%0A                    lat, lon = place.get('latitude'), place.get('longitude')%0A%0A                    try:%0A                        location, new_location = Location.objects.get_or_create(city__iexact=city, state=state)%0A                    except Location.MultipleObjectsReturned:%0A                        duplicate_locations = Location.objects.filter(city__iexact=city, state=state)%0A                        stories_at_location = duplicate_locations.values_list('story', flat=True)%0A                        duplicate_locations.delete()%0A%0A                        location = Location(city=city, state=state)%0A                        location.save()%0A%0A                        for reset_id in stories_at_location:%0A                            try:%0A                                reset_story = Story.objects.get(id=reset_id)%0A                                reset_story.location = location%0A                                reset_story.save()%0A                            except Story.DoesNotExist:%0A                                pass%0A%0A                        new_location = True%0A                        %0A                    if new_location and lat and lon:%0A                        location.city = city%0A                        location.state = state
 %0A   
@@ -4216,35 +4216,59 @@
 on.l
-on
+at
  = 
-p
 la
-ce.get('longitude')
+t%0A                        location.lon = lon
 %0A   

combine multiple locations on import