#! C:\Python27
import os
import math
import numpy as np
import pandas as pd
import cv2
import time
'''
Read binary mask of cells generated by the CellProfiler
Find coordinates of the cell outline
Organize coordinates in a dataframe
Save dataframe as a pickle to pass it to another python script
'''

#print upto 4 degits below zero
np.set_printoptions(precision=4,suppress=True)

def read_selected_imageset(masterUIpath,BuildModel=False):
	#cwd = os.path.abspath(os.path.dirname(__file__))
	#UI = pd.read_csv(cwd + '/' + 'masterUI.csv')

	UI = pd.read_csv(masterUIpath + 'masterUI.csv')

	if BuildModel:
		on = UI.build_model
		tag = 'build_model'
	else:
		on = UI.apply_model
		tag = 'apply_model'

	setpath = UI.maskset_path
	on = [0 if math.isnan(x) else x for x in on]
	index = np.argwhere(on).flatten()

	activeset = setpath[index]

	print 'converting masks from ........'
	print activeset

	cellphotos=[]
	for index, dirname in enumerate(activeset):
		dirname = dirname + '/'
		imagefolders = os.listdir(dirname)
		for folder in imagefolders:
			subdir = dirname + folder +'/'
			cellphoto = os.listdir(subdir)
			cellphoto = np.core.defchararray.add(subdir,cellphoto)
			cellphotos = np.append(cellphotos, cellphoto)
	#iterate each cell photo to record pixel coordinate into dataframe
	boundarymaster=[]
	for cellbinary in cellphotos:
		#load image
		im = cv2.imread(cellbinary)
		#find boundary using openCV function
		imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
		ret,thresh = cv2.threshold(imgray,127,255,0)
		im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
		#postprocess boundary to match with matlab
		contour = np.empty(2)
		for i in range(len(contours[0])):
			contour = np.vstack((contours[0][i][0],contour))
		contour=contour[0:-1]
		contour.T[0] = contour.T[0]+1
		contour.T[1] = contour.T[1]+1

		boundary = np.empty((2,len(contour.T[1])))
		boundary[0] = contour.T[1]
		boundary[1] = contour.T[0]
		boundary = boundary.T.astype(int)
		#record
		boundarymaster.append(boundary)

	df = pd.DataFrame(boundarymaster)
	### need to edit this specific path to relative path
	#cwd = os.path.abspath(os.path.dirname(__file__))
	#dst = cwd.replace('sourcecode','picklejar')
	#dst = dst.replace('\\','/')
	#dst = dst + '/'

	dst = masterUIpath + 'picklejar/'
	path = dst + tag + 'Vampire_Input' +'.pickle'

	if not os.path.exists(dst):
		os.makedirs(dst)
	df.to_pickle(path)
	return df
