#!/usr/bin/python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ============================ adjust path =====================================

import sys
import os

if __name__ == '__main__':
    here = sys.path[0]
    sys.path.insert(0, os.path.join(here, '..'))

# ============================ imports =========================================

import Tkinter
import time


from dustUI import dustFrame, dustGuiLib
#from   dustStyle import dustStyle


# ============================ body ============================================

class hartDeviceVariable(dustFrame.dustFrame):



    def __init__(self, parentElem, guiLock, burstControl, macAddress="Device Variable", row=0, column=0):

        # record variables
        self.guiLock = guiLock

        self.units = [0,0,0,0]
        # init parent
        frameName = 'Mote MAC: ' + macAddress
        dustFrame.dustFrame.__init__(self, parentElem, guiLock, frameName, row, column)

        # save MAC and callback
        self.macAddr = macAddress
        self.buttonCallback = burstControl

        # row 1: slide
        self.slide = [Tkinter.Scale(self.container, state=Tkinter.DISABLED, label = self.getLabel(i), orient=Tkinter.HORIZONTAL) for i in range(4)]


        self._add(self.slide[0], 1, 0, columnspan=4, rowspan=3)
        self._add(self.slide[1], 1, 4, columnspan=4, rowspan=3)
        self._add(self.slide[2], 1, 8, columnspan=4, rowspan=3)
        self._add(self.slide[3], 1, 12, columnspan=4, rowspan=3)

        # # row 1: Units
        # # constant strings
        # temp = dustGuiLib.Label(self.container,
        #                         text='Units:', anchor=Tkinter.E)
        # self._add(temp, 1, 0)
        # # row 2: Classification
        # temp = dustGuiLib.Label(self.container,
        #                         text='Classification:', anchor=Tkinter.E)
        # self._add(temp, 2, 0)


        #dynamic strings
        self.values = [dustGuiLib.Label(self.container) for i in range(4)]
        self._add(self.values[0], 4, 1)
        self._add(self.values[1], 4, 5)
        self._add(self.values[2], 4, 9)
        self._add(self.values[3], 4, 13)


        self.classification = [dustGuiLib.Label(self.container) for i in range(4)]
        self._add(self.classification[0], 5, 1)
        self._add(self.classification[1], 5, 5)
        self._add(self.classification[2], 5, 9)
        self._add(self.classification[3], 5, 13)

        # last column: burst settings
        self.checkBox = Tkinter.Checkbutton(self.container, text="Burst mode", state=Tkinter.DISABLED)
        self.buttonEnable = Tkinter.Button(self.container, text="Enable Burst", command=self._enableBurst)
        self.buttonDisable = Tkinter.Button(self.container, text="Disable Burst", command=self._disableBurst)
        self.buttonBlink = Tkinter.Button(self.container, text="Blink", command=self._blink)

        self._add(self.buttonEnable, 1, 16, columnspan=4)
        self._add(self.buttonDisable, 2, 16, columnspan=4)
        self._add(self.buttonBlink, 3, 16, columnspan=4)
        self._add(self.checkBox, 4, 16, columnspan=4)




    # ======================== public ==========================================

    def config(self, config, varIdx):
        # display/hide connection forms
        self.guiLock.acquire()

        self.slide[varIdx].config(from_=config['min'],
                             to=config['max'],
                             tickinterval = config['max']-config['min'])
        self.units[varIdx] = config['units']
        self.classification[varIdx].configure(text= self.getClassification(config['classification']))

        self.guiLock.release()

    def updateValues(self, value):

        # display/hide connection forms
        self.guiLock.acquire()

        # slide
        for i in range(len(value)):
            self.slide[i].config(state=Tkinter.NORMAL)
            self.slide[i].set(value[i])
            self.slide[i].config(state=Tkinter.DISABLED)

            # value string
            s = str(value[i])
            s += self.getUnit(self.units[i])

            self.values[i].configure(text = s)

        self.guiLock.release()

    def updateBurst(self, enabled, cmdNum):
        # display/hide connection forms
        self.guiLock.acquire()

        if cmdNum!=0:
            desc = "Burst CMD "
            desc += str(cmdNum)
            self.checkBox.configure(text=desc)

        if enabled:
            self.checkBox.select()
        else:
            self.checkBox.deselect()

        self.guiLock.release()

        # ======================== private =========================================

    def getLabel(self, x):
        return {
             0: "Primary",
             1: "Seconadry",
             2: "Tertiary",
             3: "Quaternary"
        }[x]

    def getUnit(self, x):
        return {
            12: " kPa",
            32: " deg C",
            39: " mA",
            53: " Days",
            57: " %",
            58: " V",
            170: " g",
            250: " N/A",
            251: " N/A"
        }[x]
    def getClassification(self, x):
        return {
            0: "N/A",
            64: "Temperature",
            65: "Pressure",
            86: "Voltage",
            96: "Accelaration",
            111: "Miscellaneous"
        }[x]
    def _enableBurst(self):
        self.buttonCallback(self.macAddr, 'enable')

    def _disableBurst(self):
        self.buttonCallback(self.macAddr, 'disable')

    def _blink(self):
        self.buttonCallback(self.macAddr, 'blink')



# ============================ sample app ======================================
# The following gets called only if you run this module as a standalone app, by
# double-clicking on this source file. This code is NOT executed when importing
# this module is a larger application
#
class exampleApp(object):
    def __init__(self):
        self.window = dustWindow("hartDeviceVariable",
                                 self._closeCb)
        self.guiLock = threading.Lock()
        self.frame = hartDeviceVariable(
            self.window,
            self.guiLock,
            self._burstControl,
            macAddress="FF-FF-FF-FF-FF-FF-FF-FF",
            row=0, column=0)

        updateData = [-24.5,150, 200, 250]

        configMatrix = [
            {
                'min' : -100,
                'max' : 200,
                'units': 12,
                'classification' : 65,
            },
            {
                'min': -100,
                'max': 1000,
                'units': 58,
                'classification': 86,
            },
            {
                'min': -0,
                'max': 500,
                'units': 170,
                'classification': 96,
            },
            {
                'min': 200,
                'max': 300,
                'units': 32,
                'classification': 64,
            },
        ]
        #self.frame.config(-100, 200, varIdx=0, units=12, classification=65)
        #self.frame.config(-100, 1000, varIdx=1, units=58, classification=86)
        #self.frame.config(0, 500, varIdx=2, units=170, classification=96)
        #self.frame.config(200,300, varIdx=3, units = 32, classification=64)
        self.frame.config(configMatrix[0],0)
        self.frame.config(configMatrix[1],1)
        self.frame.config(configMatrix[2],2)
        self.frame.config(configMatrix[3],3)

        #self.frame.update(-24.5, varIdx=0)
        #self.frame.update(150, varIdx=1)
        #self.frame.update(200, varIdx=2)
        #self.frame.update(250, varIdx=3)
        self.frame.updateValues(updateData)
        self.frame.updateBurst(True,3)
        self.frame.show()
        self.window.mainloop()

    def _closeCb(self):
        print " _closeCb called"

    def _burstControl(self, macAddr, cmd):
        print("Button pressed", macAddr, cmd)


if __name__ == '__main__':
    import threading
    from dustUI.dustWindow import dustWindow
    import hartDefinition

    exampleApp()