import sys
import os
import numpy as np
import glob
import cv2
import cvtools

if __name__=="__main__":

    if len(sys.argv) != 2:
        print('Please supply a directory')
        exit()

    scales = ['x1', 'x2', 'x4', 'x8', 'x16', 'x32', 'x64', 'x128']

    total_focus_files = glob.glob(os.path.join(sys.argv[1],"*_TotalFocus.png"))

    print('Found ' + str(len(total_focus_files)) + ' total focus files')

    # # process background for each set
    #
    # for scale in scales:
    #     group = []
    #     for img_file in total_focus_files:
    #         if scale in img_file:
    #             group.append(img_file)
    #
    #     all_imgs = []
    #
    #     for img_file in group:
    #         gray = cvtools.import_image(os.path.dirname(img_file), os.path.basename(img_file), raw=True, color=False)
    #         gray = cvtools.convert_to_8bit(gray)
    #         all_imgs.append(gray)
    #
    #     all_imgs = np.array(all_imgs)
    #
    #     # median and subtract
    #     med_img = np.median(all_imgs,0)
    #     for ind,img_file in enumerate(group):
    #         bg_sub = all_imgs[ind].astype('float') - med_img
    #         bg_sub_8bit = bg_sub - np.min(bg_sub)
    #         bg_sub_8bit = (2**16)*(bg_sub/np.max(bg_sub))
    #         print('saving: '+ img_file+'_bg_sub.tif')
    #         cv2.imwrite(img_file+'_bg_sub.tif',bg_sub)

    proc_results = []

    bg_sub_files = glob.glob(os.path.join(sys.argv[1], "*bg_sub*.tif"))

    mean_vals = []
    std_vals = []

    for scale in scales:
        group = []
        skip_group = False
        for img_file in total_focus_files:
            if scale in img_file:
                if scale == 'x1':
                    if 'x16' not in img_file and 'x128' not in img_file:
                        group.append(img_file)
                else:
                    group.append(img_file)

        mean_particles = []
        for ind,img_file in enumerate(group):
            show_proc = False
            if ind == 1:
                show_proc = True
            mean_particles.append(cvtools.find_particles(img_file, save_to_disk=False, min_edge=3, min_area=3, show=show_proc))
        mp_vec = np.array(mean_particles)
        #print(str(np.mean(mp_vec))+"\t"+str(np.std(mp_vec)))
        print(str(np.mean(mp_vec)))
        mean_vals.append(np.mean(mp_vec))
        std_vals.append(np.std(mp_vec))

    print(mean_vals)
    print(std_vals)