import os
import gdal
import glob
import osr

from gdalconst import *
from os.path import join

sourcePath = 'F:\\Imagery_Temp\\*.jp2'
tempTifPath = 'F:\\Imagery_Temp\\tifTemp\\'
geoPath = 'E:\\AFFS2_Imagery\\aerofly_fs_2_geoconvert\\input_aerial_images\\'
gen_prj='prj'


##COnvert Incoming usgs JP2 to tif
def convertJP(inPath,outPath,geoPath):
    ##rint 'gdal_translate -of GTiff -co COMPRESS=JPEG -co TILED=YES '+inPath+' '+outPath
    os.system('gdal_translate -of GTiff -co "TILED=YES" '+inPath+' '+outPath)
    projectTifs(outPath,geoPath);
    deleteTempTifs(tempTifPath)
            
##Project Newly created TIF to WGS84 for lat/long coords
def projectTifs(tempPath,outPath):
    print 'gdalwarp '+tempPath+' '+outPath+' -t_srs "+proj=longlat +ellps=WGS84"'
    os.system('gdalwarp '+tempPath+' '+outPath+' -t_srs "+proj=longlat +ellps=WGS84"')
    
##Clean up intermediate tif files    
def deleteTempTifs(tempTifPath):
    tempList=os.listdir(tempTifPath)
    for item in tempList:
        if item.endswith(".tif"):
            os.remove(join(tempTifPath, item))
##Get Lat/Long boundaries for TMC
def findGDALCoordinates(path):
    if not os.path.isfile(path):
        print("Ouch")
        return []
    data = gdal.Open(path,GA_ReadOnly)
    if data is None:
        print("Dang")
        return []
    geoTransform = data.GetGeoTransform()
    minx = geoTransform[0]
    maxy = geoTransform[3]
    maxx = minx + geoTransform[1]*data.RasterXSize
    miny = maxy + geoTransform[5]*data.RasterYSize
    
    print(minx,miny,maxx,maxy)
    createTMCandBAT(str(minx),str(miny),str(maxx),str(maxy))
    createTFW(geoPath, gen_prj)
    
##Calculate TFWfile
def createTFW(path, gen_prj):
    for infile in glob.glob(os.path.join(geoPath, '*.tif')):
        src = gdal.Open(infile)
        xform = src.GetGeoTransform()

        if gen_prj == 'prj':
            src_srs = osr.SpatialReference()
            src_srs.ImportFromWkt(src.GetProjection())
            src_srs.MorphToESRI()
            src_wkt = src_srs.ExportToWkt()

            prj = open(os.path.splitext(infile)[0] + '.prj', 'wt')
            prj.write(src_wkt)
            prj.close()

        src = None
        edit1=xform[0]+xform[1]/2
        edit2=xform[3]+xform[5]/2

        tfw = open(os.path.splitext(infile)[0] + '.tfw', 'wt')
        tfw.write("%0.8f\n" % xform[1])
        tfw.write("%0.8f\n" % xform[2])
        tfw.write("%0.8f\n" % xform[4])
        tfw.write("%0.8f\n" % xform[5])
        tfw.write("%0.8f\n" % edit1)
        tfw.write("%0.8f\n" % edit2)
        tfw.close()
  
##CreateTMCandBATCH files for Geocopnvert tool
def createTMCandBAT(minX,maxX,minY,maxY):
    
    f=open("E:\\AFFS2_Imagery\\aerofly_fs_2_geoconvert\\test.tmc",'w')

    f.write("<[file][][]\n")
    f.write("    <[tmcolormap_regions][][]\n")
    f.write("        <[bool]   [write_ttc_files][true]>\n")
    f.write("        <[string8][folder_destination_ttc][./scenery/images/]>\n")
    f.write("        <[bool]   [always_overwrite][true]>\n")
    f.write("\n")
    f.write("        <[list][region_list][]\n")
    f.write("\n")
    f.write("           <[tmcolormap_region][element][0]\n")
    f.write("                <[uint32]              [level]  [9]>\n")
    f.write("                <[vector2_float64]     [lonlat_min]   ["+minY+" "+maxY+"]>\n")
    f.write("                <[vector2_float64]     [lonlat_max]   ["+minX+" "+maxX+"]>\n")
    f.write("            >\n")
    f.write("\n")
    f.write("            <[tmcolormap_region][element][0]\n")
    f.write("                <[uint32]              [level]  [11]>\n")
    f.write("                <[vector2_float64]     [lonlat_min]   ["+minY+" "+maxY+"]>\n")
    f.write("                <[vector2_float64]     [lonlat_max]   ["+minX+" "+maxX+"]>\n")
    f.write("            >\n")
    f.write("\n")
    f.write("            <[tmcolormap_region][element][0]\n")
    f.write("                <[uint32]              [level]  [12]>\n")
    f.write("                <[vector2_float64]     [lonlat_min]   ["+minY+" "+maxY+"]>\n")
    f.write("                <[vector2_float64]     [lonlat_max]   ["+minX+" "+maxX+"]>\n")
    f.write("            >\n")
    f.write("\n")
    f.write("            <[tmcolormap_region][element][0]\n")
    f.write("                <[uint32]              [level]  [13]>\n")
    f.write("                <[vector2_float64]     [lonlat_min]   ["+minY+" "+maxY+"]>\n")
    f.write("                <[vector2_float64]     [lonlat_max]   ["+minX+" "+maxX+"]>\n")
    f.write("            >\n")
    f.write("\n")
    f.write("            <[tmcolormap_region][element][0]\n")
    f.write("                <[uint32]              [level]  [14]>\n")
    f.write("                <[vector2_float64]     [lonlat_min]   ["+minY+" "+maxY+"]>\n")
    f.write("                <[vector2_float64]     [lonlat_max]   ["+minX+" "+maxX+"]>\n")
    f.write("            >\n")
    f.write("        >\n")
    f.write("    >\n")  
    f.write(">\n")
    f.close()

    b=open("E:\\AFFS2_Imagery\\aerofly_fs_2_geoconvert\\Test.bat",'w')
    b.write(".\\aerofly_fs_2_geoconvert.exe test.tmc")
    b.close()

##get the list of Jpegs
jpegList = glob.glob(sourcePath)
print jpegList

##Run the Mofo
for jpeg in jpegList:
    head, tail= os.path.split(jpeg)
    tail = tail.split(".",1)[0]
    newPath=tempTifPath+tail+".tif"
    geoTifPath=geoPath+tail+".tif"
    convertJP(jpeg,newPath,geoTifPath)
    findGDALCoordinates(geoTifPath)




