#!/usr/bin/env python3
"""
Author: thnikk
"""
import time
import random
import signal
import subprocess
import os
import evdev

# Define what inputs device can use
capabilites = {1: [272, 273, 274, 275, 276, 277, 278, 279],
               2: [0, 1, 6, 8, 11, 12], 4: [4]}
# Create device
mouse = evdev.uinput.UInput(capabilites, name="autoclicker")

# Send a notification and sound when script starts/ends
sound_path = "/usr/share/sounds/freedesktop/stereo/"
statuses = [["Started", sound_path + "device-added.oga"],
            ["Stopped", sound_path + "device-removed.oga"]]


def notify(status):
    replace_id = "--replace-file=" + os.path.expanduser("~/.cache/replace-id")
    subprocess.run(["notify-send.sh", replace_id,
                    " {} autoclicker".format(statuses[status][0])])
    subprocess.run(["paplay", statuses[status][1]])


# Release mouse button when program is terminated
def handler(signum, frame):
    signame = signal.Signals(signum).name
    print(f'Signal handler called with signal {signame} ({signum})')
    mouse.write(evdev.ecodes.EV_KEY, evdev.ecodes.BTN_LEFT, 0)
    mouse.write(evdev.ecodes.EV_SYN, 0, 0)
    notify(1)
    exit(1)


# Run handler if program receives SIGTERM
signal.signal(signal.SIGTERM, handler)


# Generate a random float between 0.1 and 0.3
# This is used for sleeping between key presses to avoid detection
def getRandom():
    return round(random.uniform(0.1, 0.3), 2)


notify(0)

# Create loop
while True:
    try:
        # Press
        mouse.write(evdev.ecodes.EV_KEY, evdev.ecodes.BTN_LEFT, 1)
        mouse.write(evdev.ecodes.EV_SYN, 0, 0)
        time.sleep(getRandom())

        # Release
        mouse.write(evdev.ecodes.EV_KEY, evdev.ecodes.BTN_LEFT, 0)
        mouse.write(evdev.ecodes.EV_SYN, 0, 0)
        time.sleep(getRandom())
    # Release mouse button on keyboard interrupt (ctrl+c)
    except KeyboardInterrupt:
        handler(signal.SIGTERM, None)
