import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from django.conf import settings


from srsbrowser.models import *
from epsg.models import EpsgCoordinatereferencesystem

# wipe the old objects:

#refs = EPSG.objects.all()
#
#for ref in refs:
#    ref.delete()
    
codes = EpsgCoordinatereferencesystem.objects.all()


#print len(codes)

os.environ['GDAL_DATA']  = os.path.join(os.path.abspath('.'),'gdal')

print os.environ['GDAL_DATA']

from osgeo import gdal, osr, ogr

#osr.UseExceptions()

if gdal.GetConfigOption('GDAL_DATA', None) != os.environ['GDAL_DATA']:
    raise Exception("GDAL_DATA was not properly set!")


ref = osr.SpatialReference()
for code in codes:
    srs_id = code.coord_ref_sys_code
     
    ref.ImportFromEPSG(int(srs_id))


    text = ref.ExportToWkt()
    existing = EPSG.objects.filter(srs_id=srs_id, type='epsg')
    if existing.count() == 1:
        o = existing[0]
        if (text): 
            o.wkt = text
        o.title = code.coord_ref_sys_name
        o.epsg = code
    else:    
        o = EPSG(wkt=text, srs_id=srs_id, epsg=code, type='epsg', title=code.coord_ref_sys_name)

    o.bounds = o.get_bounds()

    print o
    o.save()

    
