from django.http import HttpResponse
import numpy as np

#Usual way of creating figures
import matplotlib.pyplot as plt

#Alternative way to display the figures
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg

#Required Imports
import matplotlib.cm as cm
from mpl_toolkits.basemap import Basemap

def create_map(ax, llcrnrlon,llcrnrlat,urcrnrlon,urcrnrlat):

    m = Basemap(llcrnrlon=llcrnrlon,llcrnrlat=llcrnrlat,urcrnrlon=urcrnrlon,
                urcrnrlat=urcrnrlat,resolution='i',projection='cyl',ax=ax,
                lon_0=(urcrnrlon+llcrnrlon)/2.,lat_0=(urcrnrlat+llcrnrlat)/2.)
    m.drawcoastlines()
    m.drawmapboundary()
    m.drawstates(linewidth=3)
    m.fillcontinents(color='lightgrey',lake_color='white')
    m.drawcountries(linewidth=3)
    return m

def plot_map_data(fig,ax):
    
    value = np.random.rand(50)*2.+-1.
    lat = np.random.rand(50)*4.+41.
    lon = np.random.rand(50)*6.-78.

    llcrnlon = lon.min()-0.5
    llcrnlat = lat.min()-0.5
    urcrnlon = lon.max()+0.5
    urcrnlat = lat.max()+0.5
    
    cmap = cm.jet
    m = create_map(ax,llcrnlon,llcrnlat,urcrnlon,urcrnlat)
    colorscale = cm.ScalarMappable()
    colorscale.set_array(value)
    colorscale.set_cmap(cmap)
    colors = colorscale.to_rgba(value)
    ax.scatter(lon,lat,c=colors,zorder=1000,cmap=cmap)
    fig.colorbar(colorscale, shrink=0.50, ax=ax,extend='both')

#Function to generate the map, and return it using a Djano HttpResponse
#When I use this, the map doesn't show up
def view_map(request):
    fig = Figure()
    canvas = FigureCanvasAgg(fig)
    ax = fig.add_subplot(111)
    maps.plot_map_data(fig,ax)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response

#Example of what the map should look like
if __name__ == "__main__":
    fig = Figure()
    fig = plt.figure()
    ax = fig.add_subplot(111)
    plot_map_data(fig,ax)
    plt.show()