#!/usr/bin/env python3
print("hello")

import sys
import os
import linuxcnc

from PyQt5 import QtCore, QtWidgets
from qtvcp.lib.keybindings import Keylookup

# Set up logging
from qtvcp import logger
log = logger.getLogger(__name__)


# Set the log level for this module
log.setLevel(logger.INFO) # One of DEBUG, INFO, WARNING, ERROR, CRITICAL

KEYBIND = Keylookup()

###################################
# **** HANDLER CLASS SECTION **** #
###################################

class HandlerClass:

    ########################
    # **** INITIALIZE **** #
    ########################
    # widgets allows access to  widgets from the QtVCP files
    # at this point the widgets and hal pins are not instantiated
    def __init__(self, halcomp,widgets,paths):
        self.hal = halcomp
        self.w = widgets
        self.PATHS = paths
    def processed_key_event__(self,receiver,event,is_pressed,key,code,shift,cntrl):
        # search for the top widget of whatever widget received the event
        # then check if it's one we want the keypress events to go to
        flag = False
        receiver2 = receiver
        while receiver2 is not None and not flag:
            if isinstance(receiver2, QtWidgets.QDialog):
                flag = True
                break
            else:
                receiver.keyPressEvent(event)
                event.accept()
                return True
        #if (event == 16777251):
        #    halbuttonclicked(self)
        # ok if we got here then try keybindings
        try:
            return KEYBIND.call(self,event,is_pressed,shift,cntrl)
        except NameError as e:
            LOG.debug('Exception in KEYBINDING: {}'.format (e))
        except Exception as e:
            LOG.debug('Exception in KEYBINDING:', exc_info=e)
            print ('Error in, or no function for: %s in handler file for-%s'%(KEYBIND.convert(event),key))
            return False
    ##########################################
    # SPECIAL FUNCTIONS SECTION              #
    ##########################################

    # at this point:
    # the widgets are instantiated.
    # the HAL pins are built but HAL is not set ready
    # This is where you make HAL pins or initialize state of widgets etc
    def initialized__(self):
        log.debug('INIT qtvcp handler')

    #######################
    # CALLBACKS FROM FORM #
    #######################
    def halbuttonclicked(self):
        log.debug('click')
        basename = self.w.lineEdit.text()
        if (basename == 'Belt 1'):
            # disable belt 5
            log.debug('click 1')
            print("Click 1")
        if (basename == 'Belt 2'):
			#  disable belt 6
            log.debug('click 2')
        if basename == 'Belt 3':
			#  disable belt 7	
            log.debug('click 3')					
        if basename == 'Belt 4':
			#  disable belt 8
            log.debug('click 4')
        if basename == 'Belt 5':
			#  disable belt 1
            log.debug('click 5')
        if basename == 'Belt 6':
			#   disable belt 2	
           log.debug('click 6, disable 2')					
        if basename == 'Belt 7':
			#	disable belt 3	
            log.debug('click 7, disable 3')	
        if basename == 'Belt 8':
			# disable belt 4
            log.debug('click 8')		
            					
    def applyClicked(self):
        basename = self.w.lineEdit.text()
        if basename == '': basename = self.w.comboBox.currentText()

        if self.w.radiobutton_vcp.isChecked():
            path = os.path.join(self.paths.PANELDIR, self.w.comboBox.currentText())
        elif self.w.radiobutton_vismach.isChecked():
            self.copySingleFile(self.paths.VISMACHDIR, self.w.filemanager.textLine.text(),
                                 basename, self.w.comboBox.currentText() )
            return
        else:
            path = os.path.join(self.paths.SCREENDIR, self.w.comboBox.currentText())

        self.copyFilesWithCheck(path, self.w.filemanager.textLine.text(),
                                 basename, self.w.comboBox.currentText() )

    ##############################
    # required class boiler code #
    ##############################

    def __getitem__(self, item):
        return getattr(self, item)
    def __setitem__(self, item, value):
        return setattr(self, item, value)

################################
# required handler boiler code #
################################

def get_handlers(halcomp,widgets,paths):
     return [HandlerClass(halcomp,widgets,paths)]
