# -*- coding: utf-8 -*-
"""
Created on Wed Nov  6 07:02:58 2019

@author: goldman3g
"""
import numpy as np
import matplotlib.pyplot as plt
import os
import csv
import sys
import re
from scipy import signal

#path = r"D:\Dropbox\Crew\Clark\PRE-6"
#path = r"D:\Dropbox\Crew\Clark\translocation"
#path = r"D:\Dropbox\Crew\Jiabei\191111"
#path = r"D:\Dropbox\Crew\Clark\Translocation\More_Examples"
#path = r"D:\Dropbox\Crew\Clark\PRE-6_TrypIRES"
#path = r"D:\Dropbox\Crew\Clark\Translocation\Good_Translocation_Traces"
path = r"F:\Backup Plus (Backup)\1.4.2022\Dynamic\s0201\ck\SecondaryEvents"

#####################################

def onclick(event):
    global nct
    global i
    

    if (event.button == 1):
        print("button=%d, x=%d, y=%d, xdata=%.2f, ydata=%.2f" %(
            event.button, event.x, event.y, event.xdata, event.ydata))
    
    if (event.button == 3):
        nct += 1 
        it = int(event.xdata/dt+0.5)
        ptm = it*dt
        print("Click %d, Index: %d, Time: %.1f" % (nct, it, ptm)) 
        if (nct == 1):            
            file = open(path + "\\" + 'LastI.txt', 'w') 
            file.write(str(i)+'\n') 
#            file.write(str(nct)+'\n')
            file.write("%d, %d\n" % (nct, it))
            file.close() 
        if (nct > 1):            
            file = open(path + "\\" + 'LastI.txt', 'a') 
            file.write("%d, %d\n" % (nct, it))
#            file.write("%d\n" % ptm)
            file.close() 
         
###########################           
            
def gfn():       # Get file names from directory
    file_list=os.listdir(path)
#    print (file_list)
    return file_list

############################

#find the time at which var variable goes through thresh either above (ud = 1)
#of below (ud = 0) and stays above or below for its mean for t + 5   

def findTime (var, thresh, ud):     #find the time at which
    if ud > 0: 
        for k in range(5,len(var)-1):
            if (var[k] > thresh ):
#             print ('Blip Up =', k)
             if (np.mean(var[k+1:k+5]) > thresh):
                 break
    else: 
        for k in range(5,len(var)-1):
            if (var[k] < thresh ):
#             print ('Blip Dn =', k)
             if (np.mean(var[k+1:k+5]) < thresh):
                 break
    return k

##########################
    
#Change frame rate here
dt = 0.04
print ("Non-ALEX time resolution = ", dt, " s")
    
plt.close('all')

T1 = 0
T2 = 0
TaccE = 0
TdonE = 0

file_list = gfn()
print ("Files: ", len(file_list))
i = 0
nct = 0   
pplist = []
print ("Stored click times:")
for fn in file_list:
    if "LastI" in fn:
        file = open(path + "\\" + 'LastI.txt', 'r') 
#        i = int(file.read(3))     #index of last opened ppfile
        i = int(file.readline(10))     #index of last opened ppfile
        for jnct in range(4):
#            try:
            clkTime = file.readline(10)     #should be 0 or 4 of these
            spl = clkTime.split(',')
#            print (spl[0], spl[1])
            if (spl[0] == '1'):
                T1 = int(spl[1])
                print (spl[0], ", T1 =", T1)
            if (spl[0] == '2'):
                T2 = int(spl[1])
                print (spl[0], ", T2 =", T2)
            if (spl[0] == '3'):
                TaccE = int(spl[1])
                print (spl[0], ", TaccE =", TaccE)
            if (spl[0] == '4'):
                TdonE = int(spl[1])
                print (spl[0], ", TdonE =", TdonE)
        file.close() 
    if "pairProf" in fn:
#        print ("filename = ", fn)
        result = re.search('file(.*).c', fn)
        if (result != None):
            pplist.append(fn)
 #           print ("result = ", result)
            if (i == 0):
                print (fn, result.group(1))
        
print ("PairProfile files: ", len(pplist))
##print (pplist) 


file = open(path + "\\" + 'GoodOnes.txt', 'r')
GOinxs = []
GOfns = []
iif = 0
#print (' ')
print ('Good Ones:')
for line in file:
#    print (line)
    spl = line.split()
    result = re.search('file(.*).c', spl[1])
    if ((nct == 0) and (i == 0)):
        print (iif, ', fileindex =', spl[0], ', filename =', spl[1], ' ', result.group(1))
    GOinxs.append(int(spl[0]))
    GOfns.append(spl[1])
    iif += 1
file.close() 

nGOs = len(GOinxs)
#print ('Number of Good Ones =', nGOs, '\n')
print ('Number of Good Ones =', nGOs)
print ("Non-ALEX time resolution = ", dt, " s")

while True: 
    
    print (" ")
#    print ("i = ", i)
#    print ('i = ', i, ', fileindex =', GOinxs[i], ', nct = ', nct)
    print ('i =', i, ', fileindex =', GOinxs[i], ', nct =', nct)
    fullname = path + "\\" + GOfns[i]
    print ("Full file name = ", fullname)
    fl = open(fullname)
    with open(fullname) as csvfile:
        
        data = list(csv.reader(csvfile))
    
#    print (len(data))
    
#    h = int(len(data)/2)   #assumes ALeX mode
    h = len(data)   #assumes ALeX mode
    
    rownum = 0	
#    don = []
    don = np.zeros(h)
    acc = np.zeros(h)
    acc = np.zeros(h)
    t = np.zeros(h)
    FRET = np.zeros(h)
    fFRET2 = np.zeros(h)
    gamma = 1.0
    alpha = 0.0
    delta = 0.0
    
    
    for row in data:
        if rownum == 0:
            print (row)
            ttle = row
        elif rownum < h+1:
            thisDon = float(row[0])/1000                 
            don[rownum-1] = thisDon
            thisAcc = float(row[1])/1000
            acc[rownum-1] = thisAcc
#            if thisDon > 0:
#                FRET.append(thisAcc/(thisDon+thisAcc))
#            thisFRET = thisAcc/(thisDon+thisAcc)
            if ((thisDon+thisAcc) == 0):
                thisFRET = 0
            else:
                
                thisFRET = (thisAcc - alpha*thisDon)/(gamma*thisDon+thisAcc - alpha*thisDon) #note delta and Alx not  used in this version
            
            '''
            if ((thisFRET > -0.1) and (thisFRET < 1.1) and (thisDon > 10.0)): 
                FRET.append(thisFRET)
            else:
               FRET.append(0.0)
            '''    
            FRET[rownum-1] = thisFRET
            t[rownum] = dt*rownum
            
#        else:
#            print (rownum, rownum - h - 1)
#            alx[rownum - h - 1] = float(row[1])/1000
                                    
        rownum += 1
        
    csvfile.close()
    
    print ("Frames: ", len(don))
    
    #for i in range (0,h-1):
    #    print (i, don[i], acc[i], alx[i])
        
    #for i in range (0,h-1):
    #    print (i, acc[i])
  #    scipy.signal.savgol_filter(x, window_length, polyorder, deriv=0, delta=1.0, axis=-1, mode='interp', cval=0.0)[source]    
    fFRET1 = signal.savgol_filter(FRET, 7, 2, deriv=0, delta=1.0, axis=-1, mode='mirror', cval=0.0)  #this filters the raw point-by-point FRET
#    dFdt = signal.savgol_filter(FRET, 151, 2, deriv=1, delta=1.0, axis=-1, mode='interp', cval=0.0)
#    dFdt = signal.savgol_filter(FRET, 151, 2, deriv=1, delta=1.0, axis=-1, mode='nearest', cval=0.0)
    fdon = signal.savgol_filter(don, 5, 2, deriv=0, delta=1.0, axis=-1, mode='mirror', cval=0.0)
    facc = signal.savgol_filter(acc, 5, 2, deriv=0, delta=1.0, axis=-1, mode='mirror', cval=0.0)
#    falx = signal.savgol_filter(alx, 5, 2, deriv=0, delta=1.0, axis=-1, mode='mirror', cval=0.0)
  
    for k in np.arange(h):
        fFRET2[k] = (facc[k] - alpha*fdon[k])/(gamma*fdon[k]+facc[k] - alpha*fdon[k]) #This is RET fro the pre-filtered donor and acceptor

    In3s = int(3.0/dt)              #index at 3 s
    AvInFRET = np.mean(fFRET2[5:In3s]) #mean over 1st 3 s
    SdInFRET = np.std (fFRET2[5:In3s]) #Std  over 1st 3 s
    AvIndon  = np.mean(don[5:In3s]) #mean over 1st 3 s
    AvInacc  = np.mean(acc[5:In3s]) #mean over 1st 3 s
#    AvInalx  = np.mean(alx[5:In3s]) #mean over 1st 3 s

#    print ('Av = ', AvInFRET, ', Std = ', SdInFRET, ' over 1st 3 s')
    print("AvFRET = %.3f, Std = %.3f in 1st 3 s" %(AvInFRET, SdInFRET))
    
#    print ("initial T2: ", T2)
    if (T2 == 0): 
        T2 = findTime(fFRET2, 0.1, 0)
    print ('T2 = ', T2)
    if (T1 == 0):
        T1 = len(don)-1
        Marg = 4.5
        while (T1 > T2):
            fThresh = AvInFRET + Marg*SdInFRET
            T1 = findTime(fFRET2, fThresh, 1)
            print ('T1 = ', T1, ', Margin = ', Marg)
            Marg -= 0.5
    else:
        print ('T1 = ', T1, 'from click')
        
    AvFRETtT1 =  np.mean(fFRET2[5:T1-4]) #mean until T1
    AvFRETT1tT2= np.mean(fFRET2[T1:T2-4]) #mean  T1 - T2
    print("AvFRET 0-T1 = %.3f, AvFRET T1-T2 = %.3f" %(AvFRETtT1, AvFRETT1tT2))
        
    if (TaccE == 0):
        TaccE = findTime(acc, 0.2*AvInacc, 0)
    print ('TaccE = ', TaccE)
    
    bbb = 50 #black bar before transition
    bab = 100   #black bar after transition

    try:
        AvDonbTaccE =  np.mean(don[TaccE-bbb:TaccE-1]) #mean donor just before ALEX ends
        AvDonaTaccE =  np.mean(don[TaccE:TaccE+bab]) #mean donor just after ALEX ends
        AvAccbTaccE =  np.mean(acc[TaccE-bbb:TaccE-1]) #mean accep just before ALEX ends
        AvAccaTaccE =  np.mean(acc[TaccE:TaccE+bab]) #mean accep just after ALEX ends
    except:
        print("Trace was too short")
        AvDonbTaccE =  0 #mean donor just before ALEX ends
        AvDonaTaccE =  0 #mean donor just after ALEX ends
        AvAccbTaccE =  0 #mean accep just before ALEX ends
        AvAccaTaccE = 0  #mean accep just after ALEX ends
        

    if (TdonE == 0):
        TdonE = findTime(don, 0.1*AvIndon, 0)
    print ('TdonE = ', TdonE)
    if (TdonE <= TaccE):
        print ("Warnng: TdonE <= TaccE")
            
#    fig1 = plt.figure(1)
    fig1, (sb1, sb2) = plt.subplots(2, sharex=True, figsize=(10, 7))
#    fig1, (sb1, sb2, sb3, sb4) = plt.subplots(4, sharex=True, figsize=(10, 11))
    fig1.suptitle(str(i)+",  "+GOfns[i], fontsize=16)
    pmngr = plt.get_current_fig_manager()
# to put it into the upper left corner for example:
    pmngr.window.setGeometry(50, 50, 900, 700)

    ylab = ''.join (('                                    ',
                 'FRET                            ',
                 'Intensity'))
    plt.ylabel(ylab, fontsize=16)
    
    sb1.set_title(ttle[0]+",   "+ttle[1], fontsize=16)
    sb1.plot(t, don, 'lime', linewidth=0.5)
    sb1.plot(t, acc, 'r', linewidth=0.5)
    sb1.plot([t[TaccE-bbb], t[TaccE-1]],  [AvDonbTaccE, AvDonbTaccE], 'black', linewidth=1)
    sb1.plot([t[TaccE]  , t[min(TaccE+bab, len(don)-1)]], [AvDonaTaccE, AvDonaTaccE], 'black', linewidth=1)
    sb1.plot([t[TaccE-bbb], t[TaccE-1]],  [AvAccbTaccE, AvAccbTaccE], 'black', linewidth=1)
    sb1.plot([t[TaccE]  , t[min(TaccE+bab, len(don)-1 )]], [AvAccaTaccE, AvAccaTaccE], 'black', linewidth=1)
    sb1.plot(t[TdonE], don[TdonE],'o',mfc='none',mec ='teal')
    sb1.plot(t[TaccE], acc[TaccE],'o',mfc='none',mec ='m')
    sb1.grid(True)
 
# Running covariance didn't work    
#    cvhw = 2    #running covariance half-window
#    cv = np.zeros(h)
#    for ck in np.arange(cvhw,h-cvhw):
#        cv[ck] = np.cov(fdon[ck-cvhw:ck+cvhw], facc[ck-cvhw:ck+cvhw], bias=True)[0][1]

#    sb2.plot(t, cv, 'lime', linewidth=0.5)
        
#    sb2.plot(t, alx, 'r', linewidth=0.5)
#    sb2.plot(t[TalxE], alx[TalxE],'o',mfc='none',mec ='DarkRed')
#    sb2.grid(True)
    
    sb2.plot(t, FRET, 'blue', linewidth=0.5)
#    sb3.plot(t, fFRET1, 'r', linewidth=0.5)
    sb2.plot(t, fFRET2, 'g', linewidth=0.5)
    sb2.plot(t[T1], fFRET2[T1],'o',mfc='none',mec ='DarkGreen')
    sb2.plot(t[T2], fFRET2[T2],'o',mfc='none',mec ='DarkViolet')
    sb2.plot([t[5], t[T1-4]], [AvFRETtT1, AvFRETtT1], 'pink', linewidth=2)
    sb2.plot([t[T1], t[T2-4]], [AvFRETT1tT2, AvFRETT1tT2], 'pink', linewidth=2)
    plt.ylim(-0.1, 1.1) 
    sb2.grid(True)


    plt.xlabel('Time (s)', fontsize=16)  
#    plt.pause(0.5)  

    textstr = '\n'.join((
    r'$T1 = $%.2f s, $AvFRET\ \ 0-T1\ = $%.3f' % (t[T1], AvFRETtT1, ),
    r'$T2 = $%.2f s, $AvFRET\ T1-T2 = $%.3f' % (t[T2], AvFRETT1tT2, )))

    props = dict(boxstyle='round', facecolor='powderblue', alpha=1)
#    props = dict(boxstyle='round', facecolor=(0,0,0,0), alpha=0.5, )
#    place a text box in upper left in axes coords
    plt.text(50, 0.75, textstr, fontsize=10,
    verticalalignment='top', bbox=props)

    plt.show()  
    plt.pause(0.7)  
    
    g = input("CR, (S)ave, (R)evisit, (B)ack, (G)oto, (C)lick, (Q)uit: ") 
#    print (g)
#    plt.close("all")
#    print (' ')
    if ((g == "b") or (g == "B")):
        i -= 2
        
    if ((g == "g") or (g == "G")):
        i = int(input("Type index number: "))
        i -= 1
        
    if g == "c" or g == "C":        
        cid = fig1.canvas.mpl_connect('button_press_event', onclick)
#        ax.set_title("click on figure")
#        plt.savefig(r'D:\Dropbox\Crew\Jiabei\191111\105.pdf')
#        print ('Ending i =', i, 'ncd = ', nct)
        print ("Right-click T1, T2, TaccE, TdonE in tha order")
        file = open(path + "\\" + 'LastI.txt', 'w') 
        file.write(str(i)+'\n') 
        file.write(str('0\n'))
        file.close() 
        nct = 0
        sys.exit()
                            
    if g == "q" or g == "Q":
        plt.close("all")
#        print ('Ending i =', i)
        file = open(path + "\\" + 'LastI.txt', 'w') 
        file.write('0\n') 
        file.write('0\n')
        file.close() 
        sys.exit()

    if g == "s" or g == "S":
        file = open(path + "\\" + 'SavedData.csv', 'a') 
        textstr = str(i)+' '+pplist[i]+'\n' 
        textstr = '%d, %d, %d, %d, %d, %d, %.3f, %.3f, %.2f, %.2f, %.2f, %.2f, %s\n' % (i, 
            GOinxs[i], T1, T2, TaccE, TdonE, AvFRETtT1, AvFRETT1tT2, 
            AvDonbTaccE, AvDonaTaccE, AvAccbTaccE, AvAccaTaccE, GOfns[i])
        print ('index, file index, T1, T2, TaccE, TdonE, AvFRET 0-T1, AvFRET T1-T2, ',
            'AvDonbTaccE, AvDonaTaccE, AvAccbTaccE, AvAccaTaccE, filename)')      
        print (textstr)
        file.write(textstr) 
        file.close() 

    if g == "r" or g == "R":
        file = open(path + "\\" + 'Revisit.csv', 'a') 
        textstr = str(i)+' '+pplist[i]+'\n' 
        textstr = '%d, %d, %d, %d, %d, %d, %.3f, %.3f, %.2f, %.2f, %.2f, %.2f, %s\n' % (i, 
            GOinxs[i], T1, T2, TaccE, TdonE, AvFRETtT1, AvFRETT1tT2, 
            AvDonbTaccE, AvDonaTaccE, AvAccbTaccE, AvAccaTaccE, GOfns[i])
        print ('index, file index, T1, T2, TaccE, TdonE, AvFRET 0-T1, AvFRET T1-T2, ',
            'AvDonbTaccE, AvDonaTaccE, AvAccbTaccE, AvAccaTaccE, filename)')      
        print (textstr)
        file.write(textstr) 
        file.close() 




    plt.close("all")
    i += 1 
    if i >= nGOs:    
        i = 0
    if i < 0:
        i = nGOs-1
    T1 = 0
    T2 = 0
    TaccE = 0
    TdonE = 0
