#Sentinel 2 MSI TCI Level 2
#both from direct download Science hub, als well as when retrieving the complete zip file
#can also be used to import e.g. AOT, SCL, VIS and WVP products available at the various resolutions

from tkinter import *
from tkinter.filedialog import askdirectory
from tkinter.filedialog import askopenfilename
from tkinter.ttk import Progressbar, Style
import os
import sys
from osgeo import gdal
import ilwis
import shutil
from threading import Thread

#passing parameters from sub menu

def execute(SentDir, InFileName, WorkDir, OutFileName, exportFormat):
    print(exportFormat)
    if len(SentDir) > 0 and len(InFileName) > 0 and len(WorkDir) > 0 and len(OutFileName) > 0:

        progress['value'] = 0

        os.chdir(WorkDir)

        shutil.copy(SentDir + '/'+ InFileName, WorkDir)

        progress['value'] = 30

        #conduct gdal warp operation using jp2 file copied from source folder and save file for ilwis or qgis processing
        input_raster = gdal.Open(InFileName)
        if exportFormat == 'ilwis':
            input_raster = gdal.Open(InFileName)
            output_raster = (OutFileName+'.mpr')
            format = 'ILWIS'
            driver = gdal.GetDriverByName( format )
            progress['value'] = 50
            gdal.Warp(output_raster,input_raster,format='ILWIS')

   
        elif exportFormat == 'qgis':
            input_raster = gdal.Open(InFileName)
            output_raster = (OutFileName+'.tif')
            format = 'GTiff'
            driver = gdal.GetDriverByName( format )
            progress['value'] = 50
            gdal.Warp(output_raster,input_raster,format='GTiff')
 

        progress['value'] = 100
    button0.config(state='normal')
    button1.config(state='normal')

#redundant files deleted in main menu script

def executeInThread(SentDir, InFileName, WorkDir, OutFileName, exportFormat):
    button0.config(state='disabled')
    button1.config(state='disabled')
    thread = Thread(target = execute, args = (SentDir, InFileName, WorkDir, OutFileName, exportFormat))
    thread.start()

#main()

sent_path = os.path.realpath('.')
print (sent_path)
os.chdir(sent_path)
os.environ["sent_lib"] = sent_path

app = Tk()
app.title("Import S2A/B L2 MSI-TCI")
app.iconbitmap(sent_path +'\pics\esa.ico')

w = 650 # width for the Tk app
h = 210 # height for the Tk app

app.geometry('%dx%d' % (w, h))
app.resizable(0,0)

labelText1 = StringVar()
labelText1.set ("""Import routine for S2A/B Level 2 MSI TCI / or AOT, SCL, VIS and WVP
Typical filename: L2A_T31UFU_20170526T105031_TCI_10m.jp2 or T31UFU_20170215T105121_TCI.jp2""")

label1 = Label(app, textvariable=labelText1, anchor='w', justify = LEFT)
label1.pack(side = LEFT)
label1.place(x = 10, y = 5, width=650, height=35)

L1 = Label(app, text="Input Directory:", anchor='w')
L1.pack(side = LEFT)
L1.place(x = 10, y = 50, width=150, height=25)

inputDir = StringVar()
E1 = Entry(app, textvariable=inputDir, bd =2)
E1.pack()
E1.place(x = 165, y = 50, width=445, height=25)

button_dirin = Button(app, text="....", width=2, command = lambda: inputDir.set(askdirectory(initialdir = inputDir.get())))
button_dirin.pack()
button_dirin.place(x = 615, y = 49)

L2 = Label(app, text="Input Filename:", anchor='w')
L2.pack(side = LEFT)
L2.place(x = 10, y = 80, width=150, height=25)

inputFile = StringVar()
E2 = Entry(app, textvariable=inputFile, bd =2)
E2.pack()
E2.place(x = 165, y = 80, width=445, height=25)

button_filein = Button(app, text="....", width=2, command = lambda: inputFile.set(askopenfilename(initialdir = inputDir.get()).split('/')[-1]))
button_filein.pack()
button_filein.place(x = 615, y = 79)

L3 = Label(app, text="Output Directory:", anchor='w')
L3.pack(side = LEFT)
L3.place(x = 10, y = 110, width=150, height=25)

outputDir = StringVar()
E3 = Entry(app, textvariable=outputDir, bd =2)
E3.pack()
E3.place(x = 165, y = 110, width=445, height=25)

button_dirout = Button(app, text="....", width=2, command = lambda: outputDir.set(askdirectory(initialdir = outputDir.get())))
button_dirout.pack()
button_dirout.place(x = 615, y = 109) 

L4 = Label(app, text="Output Filename:", anchor='w')
L4.pack(side = LEFT)
L4.place(x = 10, y = 140, width=150, height=25)

outputFile = StringVar()
E4 = Entry(app, textvariable=outputFile, bd =2)
E4.pack()
E4.place(x = 165, y = 140, width=445, height=25)

button0 = Button(app, text="Quit", width=15, command=app.destroy)
button0.pack()
button0.place(x = 525, y = 180)

exportFormat = StringVar()
   
R1 = Radiobutton(app, text="ILWIS", variable=exportFormat, value='ilwis')
R1.pack()
R1.place(x = 165, y = 180)

R2 = Radiobutton(app, text="QGIS", variable=exportFormat, value='qgis')
R2.pack()
R2.place(x = 285, y = 180)

R1.select()
R2.deselect()

button1 = Button(app, text="Execute", width=15, command=lambda: executeInThread(inputDir.get(), inputFile.get(), outputDir.get(), outputFile.get(), exportFormat.get()))
button1.pack()
button1.place(x = 405, y = 180)

style = Style()
style.theme_use('clam')
style.configure('blue.Horizontal.TProgressbar', foreground='blue', background='blue')

progress = Progressbar(app, style='blue.Horizontal.TProgressbar', orient=HORIZONTAL, length=100, mode='determinate')
progress.pack()
progress.place(x = 10, y = 180)
app.mainloop()

print("inputFile=" + inputFile.get())
print("outputDir=" + outputDir.get())
print("outputFile=" + outputFile.get())



