###############################################################################
#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 gen_tiles -s 60,6 -e 66,8 -c firetrans -b serve_tile
#
#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: Dennis Wagenaar
#
#Original Author: Anders Eriksen
#https://github.com/robertrv/django-gheat/issues/1
#
###############################################################################

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
import math

class LatLonToTile:

    def deg2num(self, lat_deg, lon_deg, zoom):
	lat_rad = math.radians(lat_deg)
	n = 2.0 ** zoom
	xtile = int((lon_deg + 180.0) / 360.0 * n)
	ytile = int((1.0 - math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad))) / math.pi) / 2.0 * n)
	return(xtile, ytile)


class Command(BaseCommand):

    option_list = BaseCommand.option_list + (
        make_option("-b", "--tileview", dest="viewname", default="serve_tile"),
        make_option("-s", "--start", dest="start", default="52.132708,4.437389"),
        make_option("-e", "--end", dest="end", default="52.178837,4.551029"),
        make_option("-c", "--colorscheme", dest="color", default="classic"),
    )

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

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

 	d2n = LatLonToTile()

        #initialize browser client
        c = Client()

	for tz in range(1, 17):
		#calculate start tiles
		mxmin, mymax = d2n.deg2num(float(start[0]), float(start[1]), tz)

		#calculate end tiles
		mxmax, mymin = d2n.deg2num(float(end[0]), float(end[1]), tz)

		#loop through each tile and generate a request to the serve_tile view using Client
		for ty in range(mymin, mymax+1):
		    for tx in range(mxmin, mxmax+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

