import nmrglue as ng
import numpy as np
import pylab as pl
from tkinter import *
from tkinter import filedialog, messagebox

root = Tk()
root.withdraw()

messagebox.showinfo('ChemSMP: Input','Please select location of directory with bruker 2rr file')
dic, data = ng.fileio.bruker.read_pdata(filedialog.askdirectory())

cutoff = 0.1
contourLevel = 3000000
status = True

while (status):

    d = cutoff * data.max()
    peaks = ng.peakpick.pick(data,pthres = d, table = True, cluster = True)

    x = []
    y = []

    for i in peaks:
        x.append(i[0])
        y.append(i[1])

    x = np.array(x)
    y = np.array(y)

    pl.cla()
    cl = [contourLevel*1.2**x for x in range(20)]
    pl.contour(data,cl)
    pl.scatter(y,x, color='red', s = 800, marker = '+',linewidths = 2)
    pl.ion()
    pl.show()

    status = messagebox.askyesno('Peaklist Check', 'Do you want to pick (visualize peaks) with changed relative intensity to peak maxima ?\n (Default is 0.1)\n Do you want to visualize peaks with changed contour level?\n (Default is 3000000)')
    if status:
        contourLevel = float(input('Lowest contour level, Change this value to visulaize peaks contour at low or high level\n'))
        cutoff = float(input('Threshold for peak picking relative to maxima ( > 0 and < 1)\n'))

class MyDialog:
    def __init__(self, parent):

        top = self.top = Toplevel(parent)

        Label(top, text="1H Spectral Width in ppm").pack()

        self.sw1h = Entry(top)
        self.sw1h.pack(padx=5)

        Label(top, text="1H Offset in ppm").pack()

        self.o1h = Entry(top)
        self.o1h.pack(padx=5)

        Label(top, text="13C Spectral Width in ppm").pack()

        self.sw13c = Entry(top)
        self.sw13c.pack(padx=5)

        Label(top, text="13C Offset in ppm").pack()

        self.o13c = Entry(top)
        self.o13c.pack(padx=5)


        b = Button(top, text="OK", command=self.ok)
        b.pack(pady=5)

    def ok(self):


        bruker_hlowlimit = float(self.o1h.get()) - (float(self.sw1h.get())/2)
        bruker_hhighlimit = float(self.o1h.get()) + (float(self.sw1h.get())/2)

        bruker_clowlimit = float(self.o13c.get()) - (float(self.sw13c.get())/2)
        bruker_chighlimit = float(self.o13c.get()) + (float(self.sw13c.get())/2)
        self.top.destroy()

        dim = data.shape
        h_ppm_per_point = abs(bruker_hlowlimit - bruker_hhighlimit)/dim[1]
        c_ppm_per_point = abs(bruker_clowlimit - bruker_chighlimit)/dim[0]

        messagebox.showinfo('Ouput','Select filename to save file')

        fw = open(filedialog.asksaveasfilename(),'w')

        for p in peaks:
            cn = p[0]
            hn = p[1]
            vol = p[5]

            cn_ppm = bruker_chighlimit - cn*c_ppm_per_point
            hn_ppm = bruker_hhighlimit - hn*h_ppm_per_point

            fw.write('%4d %3.3f %3.3f %15d\n' %(p[2], hn_ppm, cn_ppm, vol))

        fw.close()
    

d = MyDialog(root)

root.wait_window(d.top)        







