# coding: utf-8

# Author : Nitram Treblig

import lyntin.keyhook as key

from lyntin import exported

import time

class Shortcut:

  

  def __init__(self):

    # initiate internal hotkey list

    self._count = 0

    self._lastKeyUpID = 0

    self._ctrl = False

    self._vermaj = False

    self.KeyDownID = []
    self._suppressed_keys = set()

    self._content = ""

    self._hwnd = 0
    self._recovery_check = 0
    self._nvda_identity = None




    # initiate user hotkey list

    self.UserHKF = []

    self.HKFIDDict = {}



    # create Lookup for event keys and ids

    self.ID2Key, self.Key2ID = self.createKeyLookup()

    

    #creat list for merged keys like Ctrl <= Lcontrol, Rcontrol

    self.KeyID2MEID = self.createMergeKeys()

    

    # watch for all keyboard events

    key.setCallbacks(self.OnKeyUp, self.OnKeyDown)

    #key.keyDownCallback += self.OnKey

    self._global = False

    self._focus = True



  def start(self):

    """Start to check for hotkeys"""

    key.initialize()

    

  def end(self):

    """End to check for hotkeys"""

    key.terminate()  

  def pollRecovery(self):
    """Recover after NVDA restart even when the command box keeps focus."""
    now = time.monotonic()
    if now < self._recovery_check:
      return
    self._recovery_check = now + 1.0
    identity = key.nvda_identity()
    if identity != self._nvda_identity:
      self._nvda_identity = identity
      # Key releases may have been swallowed during screen reader shutdown.
      self.KeyDownID.clear()
      self._suppressed_keys.clear()
    if identity and self._hwnd == key.user32.GetForegroundWindow():
      # NVDA's window is created before its keyboard hook. Keep renewing
      # while foreground so a late hook installation cannot strand us.
      key.refresh()

  

  def isIDHotkey(self,hotkey):

    """Test if hotkey is coded in IDs"""

    for key in hotkey:

      if type(key) == str:

        return False

    return True



  def isHumanHotkey(self,hotkey):

    """Test if hotkey is coded human readable. Ex ALT F2"""

    try:

      [self.Key2ID[key] for key in hotkey]

    except:

      return False

    return True



  def hotkey2ID(self,hotkey):

    """Converts human readable hotkeys to IDs"""

    if self.isHumanHotkey(hotkey):

      return [self.Key2ID[key] for key in hotkey]

    else:

      raise Exception("Invalid Hotkey")



  def getHotkeyList(self,hotkey):

    """Create a IDlist of hotkeys if necessary to ensure functionality of merged hotkeys"""

    hotkeyVariationList = []

    hotkeyList = []

    #convert everyting into ID,MID,MEID

    if self.isIDHotkey(hotkey):

      IDHotkey = hotkey

    else:

      IDHotkey = self.hotkey2ID(hotkey)



    IDHotkeyTemp = IDHotkey[:]



    #check if there is a MEID and create accorind hotkeyVariationList

    for Key in self.KeyID2MEID:

      if self.KeyID2MEID[Key] in IDHotkeyTemp:

        #merged hotkey in hotkey

        #get MEID

        MEIDTemp = self.KeyID2MEID[Key]

        #get all KeyIDs

        KeyIDVariationTemp = [k for k in self.KeyID2MEID if self.KeyID2MEID[k] == MEIDTemp]



        #remove MEID from IDHotekey

        IDHotkeyTemp.remove(MEIDTemp)



        #store according MEID and KeyIDList

        hotkeyVariationList.append(KeyIDVariationTemp)



    if len(hotkeyVariationList) > 0:

      hotkeyVariationList.append(IDHotkeyTemp)

      #get all possible permutations

      hotkeyList = UniquePermutation(hotkeyVariationList)

    else:

      hotkeyList = [IDHotkey]



    return hotkeyList

      

  def addHotkey(self,hotkey,fun, param=[],continueEvent=False):

    """Add hotkeys with according function"""

    hotkeyList = self.getHotkeyList(hotkey)

    fhot = FHot(fun,param,continueEvent)

    newHKFID = self.getNewHKFID()

    self.HKFIDDict[newHKFID] = []



    for IDHotKeyItem in hotkeyList:

      self.UserHKF.append([IDHotKeyItem,fhot])

      self.HKFIDDict[newHKFID].append([IDHotKeyItem,fhot])

    return newHKFID

      

  def removeHotkey(self,hotkey=False, id=False):

    """Remove hotkeys and corresponding function"""

    HKFID = id

    try:

      if hotkey:

        hotkeyList = self.getHotkeyList(hotkey)

        try:

          UserHKFTemp = [[hotk, fun] for hotk, fun in self.UserHKF if not(hotk in hotkeyList)]

          self.UserHKF = UserHKFTemp[:]

        except:

          pass

      elif HKFID:

        for item in self.HKFIDDict[HKFID]:

          try:

            self.UserHKF.remove(item)

          except:

            pass

        self.HKFIDDict.pop(HKFID)

      else:

        self.UserHKF = []

    except:

      pass

      



  def setEndHotkey(self, hotkey):

    """Add exit hotkeys"""

    self.removeHotkey(self.EndHotkey)

    self.EndHotkey = hotkey

    self.addHotkey(hotkey,self.end)



#--------------------------------------------------------

#ID functions for HKFID

  def getNewHKFID(self):

    try:

      return max(self.HKFIDDict.keys())+1

    except:

      return 1

   

#--------------------------------------------------------



  def isHotkey(self,hotkey):

    """Check if hotkey is pressed down

      Hotkey is given as KeyID"""



    try:

      #make sure exact hotkey is pressed

      if not(len(hotkey) == len(self.KeyDownID)):

        return  False

      for hotk in hotkey:

        if not(hotk in self.KeyDownID):

          return False

    except:

      return False

    

    return True

  def latin(self, content):

    self._content = content

  

  def OnKeyDown(self, code, scanCode, fExtended, fInjected, hwnd):

    if fInjected:

      return True

    

    eventID = scanCode

  

    if self._global == False and self._hwnd != hwnd:

      return True

    else:

      # A consumed shortcut must also consume auto-repeat until key release.
      if eventID in self.KeyDownID:
        return not (eventID in self._suppressed_keys or 58 in self.KeyDownID)
      self.KeyDownID.append(eventID)

      for hk, fHot in self.UserHKF:

        if self.isHotkey(hk):

          import wx
          wx.CallAfter(fHot.fun, *fHot.param)

          if not fHot.continueEvent:
            self._suppressed_keys.add(eventID)

          return fHot.continueEvent



      if 58 in self.KeyDownID:
        self._suppressed_keys.add(eventID)
        return False

    return True



  def OnKeyUp(self, code, scanCode, fExtended, fInjected, hwnd):

    if fInjected:

      return True

    eventID = scanCode

    

    #exported.write_message(eventID)  

    suppressed = eventID in self._suppressed_keys
    self._suppressed_keys.discard(eventID)
    if self._global == False and self._hwnd != hwnd:
      if eventID in self.KeyDownID:
        self.KeyDownID.remove(eventID)
      return True

    ret = True

    stop = False  

    if len(self.KeyDownID) >= 2 and (29 in self.KeyDownID or 541 in self.KeyDownID or 56 in self.KeyDownID):

      if eventID in [29,56,541]:

        stop = True

    try:

      self.KeyDownID.remove(eventID)

    except:

      pass

    if suppressed:
      return False

    

    if stop:

      return ret

    

    if 58 in self.KeyDownID:

      ret = False

    


    

    return ret



  def createKeyLookup(self):

    """Creates Key look up dictionaries, change names as you please"""

    ID2Key = {

          1: 'Escape',

          2: '1',

          3: '2',

          4: '3',

          5: '4',

          6: '5',

          7: '6',

          8: '7',

          9: '8',

          10: '9',

          11: '0',

          12: 'Oem_4',

          13: 'Oem_Plus',

          14: 'Back',

          15: 'Tab',

          16: 'A',

          17: 'Z',

          18: 'E',

          19: 'R',

          20: 'T',

          21: 'Y',

          22: 'U',

          23: 'I',

          24: 'O',

          25: 'P',

          26: 'Oem_6',

          27: 'Oem_1',

          28: 'Return',

          29: 'Lcontrol',

          30: 'Q',

          31: 'S',

          32: 'D',

          33: 'F',

          34: 'G',

          35: 'H',

          36: 'J',

          37: 'K',

          38: 'L',

          39: 'M',

          40: 'Oem_3',

          41: 'Oem_7',

          42: 'Lshift',

          43: 'Oem_5',

          44: 'W',

          45: 'X',

          46: 'C',

          47: 'V',

          48: 'B',

          49: 'N',

          50: 'Oem_Comma',

          51: 'Oem_Period',

          52: 'Oem_2',

          53: 'Oem_8',

          54: 'Rshift',

          55: 'Multiply',

          56: 'Lmenu',

          58: 'Capital',

          59: 'F1',

          60: 'F2',

          61: 'F3',

          62: 'F4',

          63: 'F5',

          64: 'F6',

          65: 'F7',

          66: 'F8',

          67: 'F9',

          68: 'F10',

          69: 'Pause',

          71: 'Home',

          72: 'Up',

          73: 'Prior',

          74: 'Subtract',

          75: 'Left',

          77: 'Right',

          78: 'Add',

          79: 'End',

          80: 'Down',

          81: 'Next',

          82: 'Numpad0',

          83: 'Delete',

          86: 'Oem_102',

          87: 'F11',

          88: 'F12',

          91: 'Lwin',

          92: 'Rwin',

          93: 'Apps',

          541: 'Rcontrol',

          1010: 'Ctrl', #merged hotkeys

          1011: 'Alt',

          1012: 'Shift',

          1013: 'Win'

          }

    

    Key2ID = dict(list(map(lambda x,y: (x,y),list(ID2Key.values()),list(ID2Key.keys()))))

    

    return ID2Key, Key2ID

  

  def createMergeKeys(self):

    """Merge two keys into one

    KeyID   MEID  MergeHumanHotkey

    29   1010   Ctrl  (Lcontrol)

    541   1010   Ctrl  (Rcontrol

    56   1011   Alt   (Lmenu)

    56   1011   Alt   (Rmenu)

    42   1012   Shift (Lshift)

    54   1012   Shift (Rshift)

    91    1013   Win  (Lwin)

    92    1013   Win  (Rwin)"""



    KeyID2MEID = {29:1010,

            29:1010,

            541:1010,

            56:1011,

            42:1012,

            54:1012,

            91:1013,

            92:1013}

    return KeyID2MEID



  def getHotkeyListNoSingleNoModifiers(self):

    """return a list of all hotkeys without single events and modifiers"""

    TempID2Key = self.ID2Key.copy()



    #get rid of single events and modifiers

    getRid = [29,42,54,56,91,92]



    #get rid of Lwin and oems

    #moreRid = [186,187,188,189,190,191,192,219,220,221,222]



    #for item in moreRid:

    #  getRid.append(item)

    

    for gR in getRid:

      TempID2Key.pop(gR)



    LTempID2Key = list(TempID2Key.values())



    return LTempID2Key

    



#permutation functions needed for merged hotkeys

def UniquePermutation2(l1,l2):

  """"Return UP of two lists"""

  ltemp =[]

  for x1 in l1:

    for x2 in l2:

      ltemp.append([x1,x2])



  return ltemp



def UniquePermutation(li):

  """Return UP of a general list"""

  lcurrent = li[0]

  depth = 0

  for xl in li[1:]:

    lcurrenttemp = list()

    lcurrenttemp = UniquePermutation2(lcurrent,xl)



    if depth > 0:

      lcurrent = list()

      for item in lcurrenttemp:

        item0 = list(item[0])

        item0.append(item[1])

        lcurrent.append(item0)        

    else:

      lcurrent = lcurrenttemp[:]      

    depth += 1

  return lcurrent  



class FHot:

  def __init__(self, fun, param=[], continueEvent=False):

    self.fun = fun

    self.param = param

    self.continueEvent = continueEvent


