#!/bin/bash

# 按压和释放时间的间隔（单位：纳秒）
PRESS_THRESHOLD=300000000  # 300 毫秒
# 双击的时间间隔（单位：纳秒）
DOUBLE_CLICK_THRESHOLD=500000000  # 500 毫秒

last_press_time=0
last_click_diff=0
is_double_click=0
is_dragging=0
press_current_x=0
press_current_y=0
release_current_x=0
release_current_y=0

# 检查触摸设备函数
get_touch_id() {
    xinput list | grep -iE 'touch|waveshare|fts_ts' | grep -v 'Mouse' \
    | sed -n 's/.*id=\([0-9]\+\).*/\1/p' | awk '$1 > 6' | head -n 1
}

# 等待直到触摸设备出现
while true; do
    tc_device=$(get_touch_id)
    if [[ -n "$tc_device" ]]; then
        echo "Found touch device id: $tc_device"
        break
    fi
    #echo "Waiting for touch device..."
    sleep 5
done

xinput test $tc_device | while read -r line; do
    if [[ "$line" == *"button press"* ]]; then

        if [[ $line =~ a\[0\]=([0-9]+)\ a\[1\]=([0-9]+) ]]; then
            press_current_x=${BASH_REMATCH[1]}
            press_current_y=${BASH_REMATCH[2]}
        fi

        press_time=$(date +%s%N)

        if [[ $last_press_time -ne 0 ]]; then
            click_diff=$((press_time - last_press_time))
            
            if [[ $click_diff -lt $DOUBLE_CLICK_THRESHOLD ]]; then
                xdotool click --repeat 2 1
                is_double_click=1
            fi
        fi
        last_press_time=$press_time

    elif [[ "$line" == *"button release"* ]]; then

        if [[ $line =~ a\[0\]=([0-9]+)\ a\[1\]=([0-9]+) ]]; then
            release_current_x=${BASH_REMATCH[1]}
            release_current_y=${BASH_REMATCH[2]}
        fi  

        release_time=$(date +%s%N)
        time_diff=$((release_time - press_time))

        if [[ $press_current_x -eq $release_current_x && $press_current_y -eq $release_current_y && $time_diff -gt $PRESS_THRESHOLD ]]; then
            xdotool click 3
        fi
    fi
done