# -*- coding: utf-8 -*-
"""
Created on Tue May  3 14:11:09 2016
Assorted Auger utility functions 

@author: tkc
"""
#%%
import pandas as pd
import numpy as np
import os, glob, shutil, re # already run with functions 
import datetime
import tkinter as tk
#%%
''' RUNNING BELOW FILE MANAGEMENT UTILITIES
destdir='H:\\Research_data\\Stardust\\C2010W\\Auger\\18Nov15\\sub\\'
movefiles(spelist,destdir)

excludelist=combinelist[combinelist['Areas']==2] # finds filenames with screwed up import
AugerParamLog=removefromlog(excludelist, AugerParamLog) # removes log entries from any dataframe by filename if in excludelist

AugerParamLog=removelistdups(AugerParamLog,'Evbreaks')
'''

def compsummary(Smdifcomp, Peaks, Peaksexcl):
    ''' Compositional summary that keeps at % and identifying fields only
    can be used on integ or smdiff quant '''
    AESsumm=Smdifcomp.copy()
    mycols=['Filename', 'Sample', 'Comments', 'AESbasis', 'Phase']
    # Handle quant including the excluded elements
    missing=[i for i in Peaksexcl if i not in Peaks]
    if len(missing)>0:
        print(','.join(missing),' excluded peaks missing from peaks list')
        for i, peak in enumerate(missing):
            Peaksexcl.remove(peak)
    missing=[i for i in Peaks if i not in Smdifcomp.columns]
    if len(missing)>0:
        print(','.join(missing),' peak not present in AES smdifcomp... removed')
        for i, elem in enumerate(missing):
            Peaks.remove(elem)
    real=[i for i in Peaks if i not in Peaksexcl]
    # order with real elems first and excluded second
    for i, elem in enumerate(real):
        mycols.append('%'+elem)
    mycols.append('Total')
    if 'Total' not in AESsumm.columns:
        AESsumm['Total']=np.nan
    # put excluded peaks at the end (after total)
    for i, elem in enumerate(Peaksexcl):
        mycols.append('%'+elem)
    for index, row in AESsumm.iterrows():
        peaksumm=0.0
        # Compute at.% including all elems
        for i, elem in enumerate(Peaks):
            peaksumm+=row['%'+elem] # should be 1
        # normalize peaks to unity
        for i, elem in enumerate(Peaks):
            AESsumm=AESsumm.set_value(index,'%'+elem, 
                AESsumm.loc[index]['%'+elem]/peaksumm)
        # Redo the sum only for included (real) elems
        peaksumm=0.0
        for i, elem in enumerate(real):
            peaksumm+=row['%'+elem]
        # Now renormalize real peaks to unity 
        for i, elem in enumerate(real):
            AESsumm=AESsumm.set_value(index,'%'+elem, 
                    AESsumm.loc[index]['%'+elem]/peaksumm)
        # total shows amount of signal in real peaks
        AESsumm=AESsumm.set_value(index,'Total', 
                    peaksumm)
    AESsumm=AESsumm[mycols]
    return AESsumm


def pickspectraGUI(spelist):
    ''' Quick method of interactively selecting spectral files for plotting 
    only elements with info in quant params csv files are selectable
    returns dataframe subset (then pass to plotting functions)
    '''
    # All available elements/peaks are those with entries in Aesquantparams.csv
    files=np.ndarray.tolist(spelist.Filenumber.unique()) 
    root = tk.Tk()
    root.title('Select files for plotting or quant')
    varlist=[] # list of tkinter IntVars
    for i, col in enumerate(files): # set up string variables
        varlist.append(tk.IntVar())
        varlist[i].set(1) # default to 1
    
    def clearall():
        ''' Set all tkinter vars to zero ''' 
        for i, col in enumerate(files): # set up string variables
            varlist[i].set(0) # set default value based on elemdict

    def selectall():
        ''' Set all tkinter vars to zero ''' 
        for i, col in enumerate(files): # set up string variables
            varlist[i].set(1) # set default value based on elemdict

    def selectcombined():
        ''' Choose combined files (filenumber>100000)  ''' 
        for i, col in enumerate(files): # set up string variables
            if files[i]>100000:
                varlist[i].set(1) # set default value based on elemdict
            else:
                varlist[i].set(0) # set default value based on elemdict               

    for i, col in enumerate(files):
        # choose row, col grid position (starting row 1)
        thiscol=i%20 # 10 column setup
        thisrow=i//20
        ent=tk.Checkbutton(root, text=files[i], variable=varlist[i])
        ent.grid(row=thisrow, column=thiscol)
    # clear all 
    e=tk.Button(root, text='Clear all', command=clearall)
    lastrow=len(files)//20+1
    e.grid(row=lastrow, column=0)
    # select all 
    e=tk.Button(root, text='Select all', command=selectall)
    lastrow=len(files)//20+2
    e.grid(row=lastrow, column=0)
    e=tk.Button(root, text='Select combined', command=selectcombined)
    lastrow=len(files)//20+3
    e.grid(row=lastrow, column=0)
    # add done button
    f=tk.Button(root, text='done')
    f.bind("<Button-1>", lambda event: root.destroy())
    lastrow=len(files)//20+4
    f.grid(row=lastrow, column=0)

    root.mainloop()

    filelist=[] # list of strings with plot number and x or y
    for i, val in enumerate(varlist): # result in normal string, not tkinter StringVar