#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov  8 11:22:56 2022

@author: george
"""

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.widgets import Slider
from sklearn.neighbors import KDTree
import random
from tqdm import tqdm
import os, glob
from skimage import io
from skimage.transform import resize
from scipy.spatial import distance_matrix

import math
import numpy as np
from scipy import stats
from scipy import spatial

%matplotlib qt 

from distutils.version import StrictVersion
import flika
from flika import global_vars as g
from flika.window import Window
from flika.process.file_ import save_file_gui, open_file_gui

from qtpy.QtGui import QColor

flika_version = flika.__version__
if StrictVersion(flika_version) < StrictVersion('0.2.23'):
    from flika.process.BaseProcess import BaseProcess, WindowSelector, SliderLabel, CheckBox
else:
    from flika.utils.BaseProcess import BaseProcess, WindowSelector, SliderLabel, CheckBox

from flika import *
%gui qt

#recording options
pixelSize = 108

def loadPointData(locsFile):   
  
    ######### load FLIKA pyinsight data into DF ############
    pointsDF = pd.read_csv(locsFile)
    pointsDF['frame'] = pointsDF['frame'].astype(int)-1
    pointsDF['x'] = pointsDF['x [nm]']/pixelSize
    pointsDF['y'] = pointsDF['y [nm]']/pixelSize
                    
    return pointsDF


def loadImgData(tiffFile, transpose=False, rotateflip=True):
    #load image data
    img = io.imread(tiffFile) 
    
    if transpose == True:
        #reshape to x,y,t
        img = np.transpose(img,(1,2,0))
        
    if rotateflip == True:
        #rotate and flip for flika
        img = img[:,:,::-1]
        img = np.rot90(img, k=1, axes=(1,2))
    
    return img


def plotDataOnStack(img, points, pixelSize, crop=True):
    #plot point data on tiff stack
    
    pointWindow = Window(img)
        
    points_byFrame = points[['frame','x','y']]

    #points_byFrame['point_color'] = QColor(g.m.settings['point_color'])
    #points_byFrame['point_size'] = g.m.settings['point_size']
    pointArray = points_byFrame.to_numpy()
    
    pointWindow.scatterPoints = [[] for _ in np.arange(pointWindow.mt)]
    
    
    for pt in pointArray:
        t = int(pt[0])
        if pointWindow.mt == 1:
            t = 0
        pointSize = g.m.settings['point_size']
        pointColor = QColor(g.m.settings['point_color'])
        #position = [pt[1]+(.5* (1/pixelSize)), pt[2]+(.5* (1/pixelSize)), pointColor, pointSize]
        position = [pt[1], pt[2], pointColor, pointSize]    
        pointWindow.scatterPoints[t].append(position)
    pointWindow.updateindex()
    
      
    
if __name__ == '__main__':    
    
    locsFilePath = '/Users/george/Data/htag_cutout/GB_199_2022_09_01/GB_199_2022_09_01_locs.csv'
    #tiffFilePath = '/Users/george/Data/htag_cutout/GB_199_2022_09_01/actin_stack.tif'  
    tiffFilePath = '/Users/george/Data/htag_cutout/GB_199_2022_09_01/maxIntensity_stack.tif'      
    #tiffFilePath = '/Users/george/Data/htag_cutout/GB_199_2022_09_01/GB_199_2022_09_01_HTEndothelial_NonBAPTA_plate2_GoF_1_MMStack_Default.ome.tif'      


    locs = loadPointData(locsFilePath)
    img= loadImgData(tiffFilePath, transpose=False, rotateflip=True)    
    
    fa = start_flika()   
    plotDataOnStack(img, locs, pixelSize)
    
    #fa.close()
    
    
    
    