import os
import django.contrib.gis
from django.contrib.gis import gdal
from django.contrib.gis.gdal import HAS_GDAL
from django.contrib.gis.tests import test_gdal
from django.contrib.gis.gdal import DataSource
from string import Template

in_path = "shp/ssprec_037_s08_v01.shp"
out_path = "out/"

ds = DataSource(in_path)
n = ds.name
preclayer = ds[0]
num_feat = preclayer.num_feat
prec = preclayer[0]

# keep in mind that kml colors are aabbggrr (alpha blue green red)
kml_template = Template("""<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Document>
 	<ScreenOverlay>
		<name>California VoterConnect</name>
		<color>aaffffff</color>
		<Icon>
			<href>http://cavoterconnect.com/logo.png</href>
		</Icon>
		<overlayXY x="0" y="0" xunits="fraction" yunits="fraction"/>
		<screenXY x="0" y="0.02" xunits="fraction" yunits="fraction"/>
		<rotationXY x="0" y="0" xunits="fraction" yunits="fraction"/>
		<size x="0" y="0.1" xunits="fraction" yunits="fraction"/>
	</ScreenOverlay>
    <Style id="lbl">
      <IconStyle>
         <color>ff440044</color>
         <colorMode>random</colorMode>
         <scale>0</scale>
         <Icon>
            <href></href>
         </Icon>
      </IconStyle>
   </Style>
   <Style id="purplePrecinct">
      <LineStyle>
        <color>ff440044</color>
        <width>4</width>
      </LineStyle>
      <PolyStyle>
        <color>69ffccff</color>
      </PolyStyle>
    </Style>
  <Placemark>
    <name>precinct $name</name>
    <styleUrl>#lbl</styleUrl>
    <description>$name</description>
    <Point>
      <coordinates>$center</coordinates>
    </Point>
  </Placemark>
  <Placemark>
    <name>$name</name>
    <styleUrl>#purplePrecinct</styleUrl>
    <Polygon>
      <extrude>1</extrude>
      <altitudeMode>relativeToGround</altitudeMode>
      <outerBoundaryIs>
        <LinearRing>
          <coordinates>$coords
          </coordinates>
        </LinearRing>
      </outerBoundaryIs>
    </Polygon>
  </Placemark>
 </Document>
</kml>""")

# throttle for testing if you're whacking a big file
#num_feat = 10

numnolabel = 0

for i in range(0, num_feat):
	prec = preclayer[i]
	label = prec.get('SSPREC')
	geom = prec.geom
	geom_type = str(prec.geom_type)
	gstr = str(geom.tuple)
	# convert the slightly weird tuple format to exactly what kml wants
	g0 = gstr.replace(')),',',10')
	g1 = g0.replace('),',',10\n')
	g2 = g1.replace('(','')
	g3 = g2.replace('(((','')
	g4 = g3.replace(')','')
	# find the geometry's center to place the label
	# something weird with MultiPolygons happening, so trap the error
	try:
		ctr = str(prec.geom.centroid.tuple)
		ctr1 = ctr.replace('(','')
		ctr2 = ctr1.replace(')',',0')
	except AttributeError:
		numnolabel += 1
		print label + " is a " + geom_type
	aprec = {"name":label, "coords":g4, "center": ctr2}
	text = kml_template.substitute(aprec)
	#print text
	
	# and write out a kml file
	fname = out_path + label + '.kml'
	f = open(fname, 'w')
	f.write(text)
	f.close()

print "%d kmls created, %d with no label" % (num_feat, numnolabel)