#!python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 29 10:20:49 2019

@author: -
"""
import os, argparse, re, shutil, glob


def search_files(directory='.', extension='tif', resolution='NDVI'):
    images=[]
    extension = extension.lower()
    resolution = resolution.lower()
    
    for dirpath, dirnames, files in os.walk(directory):
        for name in files:
            if extension and name.lower().endswith(extension) and name.lower().find(resolution) >= 0 :
                
                #print(os.path.join(dirpath, name))
                abspath = os.path.abspath(os.path.join(dirpath, name))
                images.append(abspath)

    print(str(len(images)) + " image(s) found")
    return images





if __name__ == "__main__":
    # Make parser object
    parser = argparse.ArgumentParser(description=
        """
        Rename MV and NDVI
        """)
    
    parser.add_argument('-movedir', action='store', required=True, help='Directory containing Soil Moisture files (MV + NDVI) to be renamed and moved')
    parser.add_argument('-proddir', action='store', required=True, help='Destination directory')
    parser.add_argument('-prodsite', action='store', required=True, help='Production site name to be added in file naming')
    parser.add_argument('-over', action='store_true', required=False, default=False, help='Overwrite already existing files in prod dir')

    args=parser.parse_args()
    
    ndvis = search_files(args.movedir)
    
    moists = search_files(args.movedir, resolution='mv')
    
    ndvidir =os.path.join(args.proddir, "NDVI")
    s1adir =os.path.join(args.proddir, "S1A")
    s1bdir =os.path.join(args.proddir, "S1B")
    
    if not os.path.exists(args.proddir):
        os.mkdir(args.proddir)
    if not os.path.exists(ndvidir):
        os.mkdir(ndvidir)
    if not os.path.exists(s1adir):
        os.mkdir(s1adir)
    if not os.path.exists(s1bdir):
        os.mkdir(s1bdir)
    
    for n in ndvis:
        nsplit = os.path.basename(n)[:-4].split('_')
        
        fdate = re.findall("20\d{4}",n)
        if not(fdate):
            print("Impossible de trouver la date dans le nom de fichier : "+n)
            exit
        
        newname = "NDVI_"+args.prodsite.upper()+"_"+fdate[0]+".TIF"
        fannee = fdate[0][0:4]
        fmois = fdate[0][4:6]
        annee = int(fannee)
        if fmois in ["01","02","03","04","05","06","07","08"]:
            dirsais = str(annee-1)+"-"+fannee
        else:
            dirsais = fannee+"-"+str(annee+1)
            
        if not os.path.exists(os.path.join(ndvidir,dirsais)):
            os.mkdir(os.path.join(ndvidir,dirsais))
            
        newpath = os.path.join(ndvidir,dirsais,newname)
        
        print("moving : "+n)
        print("to : "+newpath+"\n")
        shutil.move(n,newpath)
        
    for m in moists:
        nsplit = os.path.basename(m)[:-4].split('_')
        
        fdate = re.findall("20\d{6}T\d{6}",m)
        if not(fdate):
            print("Impossible de trouver la date dans le nom de fichier : "+m)
            exit
            
        sat=None
        dirsat=None
        rechS1A=re.search("S1A",m)
        rechS1B=re.search("S1B",m)
        if None != rechS1A and rechS1A.start() >= 0 :
            sat="S1A"
            dirsat=s1adir
        elif None != rechS1B and rechS1B.start() >= 0 :
            sat="S1B"
            dirsat=s1bdir
        else:
            print("Impossible de trouver le satellite dans le nom de fichier : "+m)
            exit
            
        newname = "MV_"+sat+"_"+args.prodsite.upper()+"_"+fdate[0]+".TIF"
        fannee = fdate[0][0:4]
        fmois = fdate[0][4:6]
        annee = int(fannee)
        if fmois in ["01","02","03","04","05","06","07","08"]:
            dirsais = str(annee-1)+"-"+fannee
        else:
            dirsais = fannee+"-"+str(annee+1)
            
        if not os.path.exists(os.path.join(dirsat,dirsais)):
            os.mkdir(os.path.join(dirsat,dirsais))
            
        newpath = os.path.join(dirsat,dirsais,newname)
        
        if os.path.exists(newpath) and args.over: 
            delname = "MV_"+sat+"_"+args.prodsite.upper()+"_"+fdate[0]+".*"
            delpath = os.path.join(dirsat,dirsais,delname)
            for delfile in glob.glob(delpath):
                os.remove(delfile)
        elif os.path.exists(newpath) and not args.over:
            print("Already exist. No override opt")
            continue
        
        print("moving : "+m)
        print("to : "+newpath+"\n")
        shutil.move(m,newpath)
        
            
        
    
