#!/usr/bin/env pythonw

# System imports
import argparse
import os
from joblib import Parallel, delayed

# Scientific package imports
import pandas as pd

# Local imports
from xptools.utils import videotools
from xptools import analyze_front

#Setup parser
ap = argparse.ArgumentParser()
ap.add_argument("directory", nargs='?', default=os.getcwd(), help="Path of the directory")
ap.add_argument("-r", "--reprocess", action='store_true', help="Force the reprocessing of the movies")
ap.add_argument("-p", "--plotly", action='store_true', help="Use plotly instead of matplotlib for graphing")
ap.add_argument("-s", "--save", action='store_true', help="Save the resulting plot")
ap.add_argument("-c", "--scale", type=float, default=1, help="Scale factor in px/mm (default = 1)")
ap.add_argument("-f", "--framerate", type=int, default=1, help="Frame rate (default = 1)")
ap.add_argument("-a", "--autoprocess", action='store_true', help="Attempt to detect when the ice first appears")

#Retrieve arguments
args = ap.parse_args()

dirname = args.directory
bReprocess = args.reprocess
bPlotly = args.plotly
bSave = args.save
scale = args.scale
framerate = args.framerate
bAuto = args.autoprocess

if os.path.isfile(dirname) and dirname.endswith('.avi'):
    file_list=dirname
elif os.path.isdir(dirname):
    file_list = [dirname + '/' + file for file in os.listdir(dirname) if file.endswith('.avi')]
else:
    raise ValueError('Invalid file or directory.')

if len(file_list) == 0:
    raise Exception('No video file in directory.')

print("Files to process: " + str(file_list))

#Save path for the processed dataframe
savepath = dirname+"/"+"ProcessedData"+".pkl"

#If the movies have been processed already, load from disk, otherwise process now
if os.path.isfile(savepath) and not bReprocess:
    df = pd.read_pickle(savepath)
    print("Data loaded from disk")
else:
    print("Processing movies")
    df_crop = videotools.obtain_cropping_boxes(file_list)
    #Make a list with file names and cropping boxes
    vid_list = []
    for file in file_list:
        name = file.split('.')[0].split('/')[-1]
        cropping_box = df_crop[df_crop['ExpName'] == name]['CroppingBox'].iloc[0]
        vid_list.append((file, cropping_box))
    #Run the movie analysis in parallel (one thread per movie)
    df_list = Parallel(n_jobs=-2, verbose=10)(delayed(analyze_front.process_movie)(file, box, scale, framerate, bAuto) for (file, box) in vid_list)
    #Merge all the dataframes in one and reindex
    df = pd.concat(df_list).reset_index(drop=True)
    #Save dataframe to disk
    df.to_pickle(savepath)

if bPlotly:
    analyze_front.plot_front_position_pltly(df, bSave, dirname)
else:
    analyze_front.plot_front_position(df, bSave, dirname)