class DeviceTable(QtGui.QDialog):

    def __init__(self, parent=None):
        super(DeviceTable, self).__init__(parent)

        self.logger = logging.getLogger('console')
        
        self.records = {}
        
        self.resize(800,800)
        
        self.label_a = QLabel()
        self.label_a.setText("A: ")
        self.spinbox_a = QSpinBox()
        self.spinbox_a.setRange(-103,-38)
        self.spinbox_a.setValue(-41)
        self.spinbox_a.valueChanged.connect(self.spinboxChanged)
        self.spinboxChanged(self.spinbox_a.value())
        
        self.slider_label = QLabel()
        self.slider_label.setText("   n:")
        self.slider = QSlider()
        self.slider.setOrientation(QtCore.Qt.Horizontal)
        self.slider.setRange(0, 40)
        self.slider.setValue(22)
        self.slider.setTickInterval(1)
        self.slider.valueChanged.connect(self.sliderChanged)
        self.sliderChanged(self.slider.value())
        
        self.button_reset = QPushButton()
        self.button_reset.setText("Reset")
        self.button_reset.clicked.connect(self.reset)
        
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.addWidget(self.label_a)
        self.horizontalLayout.addWidget(self.spinbox_a)
        self.horizontalLayout.addWidget(self.slider_label)
        self.horizontalLayout.addWidget(self.slider)
        self.horizontalLayout.addWidget(self.button_reset)
        
        self.table = QTableWidget()  
        self.table.setColumnCount(8)
        self.table.setHorizontalHeaderLabels(['MAC','Count','RSSI','RSSI','Distance','RSSI_F', 'DIST_F','Battery'])
        
        # matplotlib stuff
        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NavigationToolbar(self.canvas, self)
        self.buttonPlot = QPushButton('Plot')
        self.buttonPlot.clicked.connect(self.plot)
        self.plot_layout = QtGui.QVBoxLayout()
        self.plot_layout.addWidget(self.toolbar)
        self.plot_layout.addWidget(self.canvas)
        self.plot_layout.addWidget(self.buttonPlot)
        self.ax = self.figure.add_subplot(111)
        self.ax.hold(False)

                
        self.statusbar = QStatusBar()
        self.statusbar.showMessage('Opening log file')
        
        self.verticalLayout = QtGui.QVBoxLayout()
        self.verticalLayout.addWidget(self.table)
        self.verticalLayout.addLayout(self.plot_layout)
        self.verticalLayout.addWidget(self.statusbar)
        
        self.mainLayout = QtGui.QVBoxLayout(self)
        self.mainLayout.addLayout(self.horizontalLayout)
        self.mainLayout.addLayout(self.verticalLayout)
        
        self.is_recording = False
        self.data = [-50]
        self.data_f = [-50]
        self.data_y = [0]

    def showEvent(self, *args, **kwargs):
        self.parent().ble_ascii_received.connect(self.bleAsciiReceived)
        return QtGui.QDialog.showEvent(self, *args, **kwargs)
    
    def closeEvent(self, *args, **kwargs):
        self.reset()
        self.parent().ble_ascii_received.disconnect(self.bleAsciiReceived)
        return QtGui.QDialog.closeEvent(self, *args, **kwargs)
    
    def spinboxChanged(self, value):
        self.distance_A = value;
    
    def sliderChanged(self, value):
        self.distance_n = value / 10.0;
        self.slider_label.setText("n [{0:.1f}]: ".format(self.distance_n))
    
    def reset(self):
        self.table.setRowCount(0)
        self.records = {}
        try:
            self.file.close()
        except Exception:
            pass
        self.file = None
        self.is_recording = False
     
    def plot(self):
        data = [random.random() for i in range(10)]
        self.ax = self.figure.add_subplot(111)
        self.ax.hold(False)
        self.ax.plot(data, '*-')
        self.canvas.draw()
                
    def startRecording(self):
        self.filename = "./logs/" + time.strftime("%y%m%d-%H%M%S") + ".txt"
        try:
            if not os.path.exists("./logs"):
                os.makedirs("./logs")
            self.file = open(self.filename, "w")
            self.statusbar.showMessage("Recording to " + self.filename)
            self.is_recording = True
        except Exception, e:
            self.file = None
            self.is_recording = True
            self.logger.error(e)
            self.statusbar.showMessage("NOT RECORDING - check console log for errors")