###############################################################################
#Management command to generate tiles using gheat.
#
#Must be given a bounding box by using options -s and -e (start and end)
#
#Example usage:
#>>> python manage.py generate_tiles -s 60,6 -e 66,8 -z 10 -c firetrans -v serve_tile
#
#Requires the globalmaptiles.py file. Get it from
#http://www.maptiler.org/google-maps-coordinates-tile-bounds-projection/globalmaptiles.py
#
#Note: This command will NOT create tiles if they are empty. In order to do so, change
#the gheat generate_tile view so that it creates empty tiles for each request given
#x and y and zoom. This way you wan't have "holes" in the tile overlay if using
#the static tiles instead of the usual django url/view.
#
#Author: Anders Eriksen
###############################################################################



from django.core.management.base import BaseCommand
from optparse import OptionParser, make_option
from django.core.urlresolvers import reverse
from django.test.client import Client
from gheat.globalmaptiles import *


class Command(BaseCommand):

    option_list = BaseCommand.option_list + (
        make_option("-b", "--tileview", dest="viewname", default="serve_tile"),
        make_option("-z", "--zoom", dest="zoomlevel", default=1),
        make_option("-s", "--start", dest="start", default="60,6"),
        make_option("-e", "--end", dest="end", default="62,6"),
        make_option("-c", "--colorscheme", dest="color", default="fire"),
    )

    def handle(self, *args, **options):

        profile = 'mercator'
        zoomlevel = None
        lat, lon, latmax, lonmax, baseurl = None, None, None, None, None
        boundingbox = False

        start = options['start'].split(',')
        end = options['end'].split(',')
        viewname = options['viewname']
        colorscheme = str(options['color'])

        #create bounding box from start latlon and end latlon
        boundingbox = (float(start[0]), float(start[1]), float(end[0]), float(end[1]))

        tz = int(options['zoomlevel'])
        mercator = GlobalMercator()

        #calculate start tiles
        mx, my = mercator.LatLonToMeters(float(start[0]), float(start[1]))
        tminx, tminy = mercator.MetersToTile(mx, my, tz)

        #calculate end tiles
        mx, my = mercator.LatLonToMeters(float(end[0]), float(end[1]))
        tmaxx, tmaxy = mercator.MetersToTile(mx, my, tz)

        #initialize browser client
        c = Client()

        #loop through each tile and generate a request to the serve_tile view using Client
        for ty in range(tminy, tmaxy+1):
            for tx in range(tminx, tmaxx+1):

                tileurl = reverse(viewname, kwargs={'color_scheme': colorscheme, 'zoom':tz, 'x':tx, 'y':ty})

                generate_response = c.get(tileurl)

                #lousy error handling. Should check why status 200 not returned... I.e. wrong colorscheme
                if generate_response.status_code == 200:
                    print "Generated tile " + tileurl
                else:
                    print "Failed generating tile " + tileurl

