import vtk
import numpy as np
import random
import platform
import sys
import os
import math
import time
import scipy.cluster.hierarchy as hc
from matplotlib import pyplot as plt
#from mpi4py import MPI
from sklearn.cluster import KMeans
from scipy.ndimage.measurements import label
from scipy.ndimage.morphology import generate_binary_structure
from mfix_fcc_sampling_bubble_detect import detect_bubbles,create_histogram,sample_data,getVtkImageData,sample_data_from_histogram,compute_entropy_from_histogram


#print(generate_binary_structure(3,2))

## first try to get the whole range
machine = platform.system()
# read this pvtp file
# if machine == 'Linux':
#     path = '/media/biswas/29d42253-dbfd-4e49-bc64-61662de409e0/MFIX/fcc-data/vtm_data/'
# elif machine == 'Darwin':
#     path = '/Users/biswas/Work/MFIX/fcc/'
# else:
#     print("Unknown machine. Add to the list")
#     exit(0)

path = './test_fcc_data/'    

file_name2 = ".vtm"
name_string = 'MFIX_fcc_vtm_' #'test_MFIX_50000'

#in_file = '/Users/biswas/Work/MFIX/fcc/timestep_408.vtm'
in_file = path+name_string+file_name2

sample_fraction = 0.05

#sample_data(in_file,name_string+file_name2,sample_fraction)
#create_histogram(in_file,name_string,sample_fraction)
#detect_bubbles(in_file,name_string,sample_fraction)

use_common_hist = 0
## run for all files
input_path = path
# tot_files = np.size(os.listdir(input_path))
# all_files = os.listdir(input_path)
# print(tot_files, all_files)
#
if use_common_hist:
    bound_min = np.load('npy_files/bound_min_' + name_string + '.npy')
    bound_max = np.load('npy_files/bound_max_' + name_string + '.npy')
else:
    bound_min = None
    bound_max = None

#entropy_list = []
for i in sorted(os.listdir(input_path)):
    # read files
    filename, file_extension = os.path.splitext(i)
    # print(filename)
    if file_extension != ".vtm":
        continue
    print("opening", i)
    # write the actual code here

    #sample_fraction = 0.1
    in_file = input_path + i


    create_histogram(in_file, filename, sample_fraction,bound_min,bound_max)
    detect_bubbles(in_file, filename, sample_fraction)

#np.save('fcc_ent',entropy_list)