import random
import simplejson
import base64
import urllib
import re
from datetime import datetime, timedelta

from django.core.cache import cache
from django.http import Http404
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt  #TODO - fix this
from django.conf import settings

from google.appengine.api import taskqueue
from google.appengine.api.memcache import Client as CacheClient
from gmp.models import Photo, Region, Organization
from utils.utils import set_trace

@csrf_exempt
def rebuild_chrono_cache_year_and_season(request, year, season):
    """
    Rebuild chrono cache for given year and season
    """
    cached_photos = Photo.objects.filter(in_chrono_cache=True, taken_year=int(year), taken_season=int(season))
    for p in cached_photos:
        p.in_chrono_cache=False
        p.save(no_cache_handling=True)

    candidate_photos = Photo.objects.filter(taken_year=int(year), taken_season=int(season))
    candidate_photos = Photo.filter_ok_moderation_statuses(candidate_photos)
    candidate_photos = candidate_photos[:Photo.NUM_IN_CHRONO_CACHE]
    for p in candidate_photos:
        p.in_chrono_cache=True
        p.save(no_cache_handling=True)

    photos_in_cache = Photo.objects.filter(in_chrono_cache=True, taken_year=int(year), taken_season=int(season))
    return HttpResponse(simplejson.dumps({
        'photos': [p.get_metadata() for p in photos_in_cache]
    }))


@csrf_exempt
def rebuild_map_cache_region(request, region_id):
    """
    Rebuild map cache for given region
    """
    cached_photos = Photo.objects.filter(in_map_cache=True, region__id=int(region_id))
    for p in cached_photos:
        p.in_map_cache=False
        p.save(no_cache_handling=True)

    candidate_photos = Photo.objects.filter(region__id=int(region_id))
    candidate_photos = Photo.filter_ok_moderation_statuses(candidate_photos)
    candidate_photos = candidate_photos[:Photo.NUM_IN_MAP_CACHE]
    for p in candidate_photos:
        p.in_map_cache=True
        p.save(no_cache_handling=True)

    photos_in_cache = Photo.objects.filter(in_map_cache=True, region__id=int(region_id))
    return HttpResponse(simplejson.dumps({
        'photos': [p.get_metadata() for p in photos_in_cache]
    }))


@csrf_exempt
def rebuild_chrono_cache(request):
    """
    Rebuild chrono cache for given year and season
    """
    for season in range(0, 4):
        for year in range(1900, datetime.now().year):
            taskqueue.add(url=reverse('rebuild_chrono_cache_year_and_season', args=[year, season]))
    return HttpResponse('OK')


@csrf_exempt
def rebuild_map_cache(request):
    """
    Rebuild map cache for all regions
    """
    for r in Region.objects.all():
        taskqueue.add(url=reverse('rebuild_map_cache_region', args=[r.id]))
    return HttpResponse('OK')


def clear_memcaches(request):
    #cache.delete('MAP_CACHE')
    #cache.delete('CHRONO_CACHE')
    #cache.delete('NEW_PHOTOS')
    #cache.delete('HIGH_SCORE_PHOTOS')
    c = CacheClient()
    c.flush_all()
    return HttpResponse('OK')


def bugfix327_prepare(request):
    """
    retrieve all photos by channel 2, and update their
    owner name
    """
    organization_id = 158001
    org = Organization.objects.get(id = organization_id)
    photos = Photo.objects.filter(organization = org)

    return HttpResponse(simplejson.dumps({
        'total': photos.count(),
        'photos': [p.get_metadata() for p in photos]
    }))

def bugfix327_apply(request):
    """
    retrieve all photos by channel 2, and update their
    owner name
    """
    organization_id = 158001 #channel 2
    org = Organization.objects.get(id = organization_id)
    photos = Photo.objects.filter(organization = org)

    start = int(request.GET.get('start', 0))
    limit = int(request.GET.get('limit', 10))

    count = 0
    for p in photos[start:limit]:
        p.owner_username = org.name
        p.save(no_cache_handling=True)
        count += 1

    return HttpResponse('done. updated %d photos' % count)


def bugfix336_prepare(request):
    """
    find all users with same email (really should be same user), and the find all photos for those users
    """
    email = request.GET['email']
    users = User.objects.filter(email = email)
    user_data = [{'id': u.id, 'username': u.username, 'email': u.email} for u in users]
    photo_data = []
    for u in users:
        photos = Photo.objects.filter(owner = u)
        photo_data.append([p.get_metadata() for p in photos])
    return HttpResponse(simplejson.dumps({
        'users': user_data,
        'photos': photo_data
    }))


def bugfix336_apply(request):
    email = request.GET['email']
    users = User.objects.filter(email = email)
    the_chosen_one = users[0]
    for i, u in enumerate(users):
        if i==0:
            continue
        photos = Photo.objects.filter(owner = u)
        for p in photos:
            p.owner = the_chosen_one
            p.save(no_cache_handling=True)
        u.email = 'qa%d_%s' % (i, u.email)
        u.save()
    return HttpResponse('done')
    


def bugfix154_prepare(request):
    """
    find all pictures without thumbnail or thumbnail_16_9 and save them to update thumbnails
    """
    photos = [p for p in Photo.objects.all() if (not p.thumbnail or not p.thumbnail_16_9)]
    return HttpResponse(simplejson.dumps({
        'photos': [p.get_metadata() for p in photos]
    }))

@csrf_exempt
def bugfix154_apply(request):
    if request.GET.get('all', False):
        for i, p in enumerate(Photo.objects.all()):
            if (not p.thumbnail or not p.thumbnail_16_9):
                taskqueue.add(url=reverse('bugfix154_apply'), params= {
                    'start': i, 'limit': i+1 })

    start = int(request.REQUEST.get('start', 0))
    limit = int(request.REQUEST.get('limit', Photo.objects.count()))
    for p in Photo.objects.all()[start:limit]:
        p.thumbnail = p.thumbnail_16_9 = None
        p.save(no_cache_handling=True)

    return HttpResponse('done')
