#!/usr/bin/python3

import os

if "DISPLAY" not in os.environ or os.environ["DISPLAY"] is None:
  os._exit(0)

import evdev
from evdev import InputDevice
import time
from pynput.mouse import Button, Controller
from threading import Timer
import subprocess

devices = [evdev.InputDevice(path) for path in evdev.list_devices()]
for device in devices:
  if device.name == "WCOM50C1:00 2D1F:5143":
    dev = InputDevice(device.path)

m = Controller()
lasttime = time.time()
rlasttime = time.time()
originaltime = lasttime
oldclickx = 0
oldclicky = 0

if "XDG_CURRENT_DESKTOP" in os.environ and (os.environ["XDG_CURRENT_DESKTOP"] == "GNOME" or os.environ["XDG_CURRENT_DESKTOP"] == "KDE"):
  subprocess.run(["sleep", "infinity"])

for event in dev.read_loop():

    if event.type == 3 and event.code == 47 and event.value == 1:
        rclicktime = time.time()
        if (rclicktime - rlasttime) < .5:
            rlasttime = rclicktime
        else:
            print("Two Finger tap.")
            subprocess.check_call(['xinput', '--disable', 'WCOM50C1:00 2D1F:5143'])
            #x2, y2 = m.position()  # Get the pointer coordinates
            m.click(Button.right, 1)
            subprocess.check_call(['xinput', '--enable', 'WCOM50C1:00 2D1F:5143'])
            rlasttime = rclicktime

    elif event.type == 1 and event.code == 330 and event.value == 1:
        clicktime = time.time()
        clickx, clicky = m.position
        if (clicktime - lasttime) < .7 and (abs(clickx - oldclickx) < 120) and (abs(clicky - oldclicky) < 20):
            print("Double click.")
            subprocess.check_call(['xinput', '--disable', 'WCOM50C1:00 2D1F:5143'])
            #x2, y2 = m.position()
            m.click(Button.left, 2)
            subprocess.check_call(['xinput', '--enable', 'WCOM50C1:00 2D1F:5143'])
            lasttime = originaltime
        else:
            lasttime = clicktime
        oldclickx = clickx
        oldclicky = clicky
