from django.forms import ModelForm
from srsbrowser.models import *
from django.utils.safestring import mark_safe
from django import forms
from django.forms.util import ValidationError
from osgeo import osr
from django.contrib.gis.gdal import SpatialReference as geodjango_sr
from django.contrib.gis.gdal.error import SRSException

import re

proj_regex = re.compile(r'^\+proj')
epsg_regex = re.compile('^(EPSG:)?(?P<epsg>\d+)$', re.I)

#widget=forms.HiddenInput

class Upload(ModelForm):
    title = forms.CharField(widget=forms.TextInput(attrs={'size':'70','class': 'required'}), required=True)
    description = forms.CharField(widget=forms.Textarea(attrs={'cols':'70', 'rows':'3','class': 'required'}), required=True)
    wkt  = forms.CharField(label='WKT',widget=forms.Textarea(attrs={'cols':'70', 'rows':'5','class': 'required'}), required=True)
    bounds = forms.CharField(widget=forms.HiddenInput, required=False)
        
    class Meta:
        model = SRS 
        exclude = ('creator', 'slug','views','pub_date','bounds','type', 'srs_id')

    def clean_wkt(self):
        srs_input = self.cleaned_data['wkt'].strip('\'"')
        try:   
            ogr_sr = osr.SpatialReference(str(srs_input))
            if ogr_sr.ExportToWkt() == '':
                raise Exception("Unable to get any WKT back.")
        except SRSException, E:
            raise ValidationError("Sorry, that does not look like valid Well Known Text")
        except Exception, E:
            raise ValidationError("Unable to validate the text you used. (Error: %s)" % E)

        #matchable = sr.wkts.lower().replace('\n','')
        srs_match = SRS.objects.filter(wkt__icontains=srs_input)
        if srs_match:
            url = srs_match[0].get_absolute_url()
            raise ValidationError(mark_safe('Hey, it seems we already have that projection at: <a href="%s">%s</a>' % (url,url)))
        return srs_input

    #def clean_bounds(self):
     #   bounds = self.cleaned_data['bounds']
        #print bounds
        #import pdb;pdb.set_trace()
      #  return bounds

    def clean(self):
        cleaned_data = self.cleaned_data
        if cleaned_data.get('wkt'):
          srs_input = self.cleaned_data['wkt']
          sr = geodjango_sr(srs_input)
          epsg_m = epsg_regex.match(srs_input)
          proj_m = proj_regex.match(srs_input)
  
          #if self.cleaned_data.has_key['from_esri']:
          #    if epsg_m:
          #        raise ValidationError("Sorry, your projection data looks like and epsg code, so please don't check the 'From Esri' box.")
          #    elif proj_m:
          #        raise ValidationError("Sorry, your projection data looks like proj4 syntax, so please don't check the 'From Esri' box.")
          #    else:
          #        sr.from_esri()
          #        self.cleaned_data['wkt'] = sr.wkt
  
        return self.cleaned_data
