#!/usr/bin/python
"""
Usage:
PYTHONPATH="../.." DJANGO_SETTINGS_MODULE="settings" python load_user.py sr.org3
"""
import psycopg2
import osr
import sys
from srsbrowser.models import SRS

db = psycopg2.connect("dbname=%s" % sys.argv[1])
db.set_client_encoding('UTF8')

cur = db.cursor()
cur.execute("SELECT id, title, description, slug, proj4, views FROM references_reference");
for row in cur.fetchall():
    (id, title, description, slug, proj4, views) = row
    srs = SRS.objects.filter(type='sr-org', srs_id=id)
    if srs.count():
        print "Skipping %s" % id
        continue
    sr = osr.SpatialReference() 
    sr.SetFromUserInput(str(proj4)) 
    try:
        wkt = sr.ExportToWkt()
    except Exception, E:
        print "Error on %s / %s: %s" % (id, proj4, E)
        continue
    if not wkt:
        print "No wkt for %s / %s" % (id, proj4)
        continue
    srs = SRS(type="sr-org", srs_id=id, title=title, description=description, slug=slug, wkt=wkt, views=views)
    srs.save()
    print "Saved %s as %s" % (id, srs.id)
