#!/usr/bin/env python3
'''
Meant to run on your PC.
Receives data generated by rmServerWacomInput.py,
moves the mouse and presses accordingly.
Configure area below!
'''


import socket
import struct
from pynput.mouse import Button, Controller
from sys import argv

#from kalman_filter import KalmanFilter
#import numpy as np

mouse = Controller()

def mouseMoveAbs(x, y):
	'''The 'mouse.move()' method only moves relative.
	   This funtion works with absolute values.'''
	#print(x, y)
	pos = mouse.position
	x = max(x, 0)
	y = max(y, 0)
	x = max(x, SCREEN_DRAW_AREA_FROM_X)
	y = max(y, SCREEN_DRAW_AREA_FROM_Y)
	x = min(x, SCREEN_DRAW_AREA_TO_X)
	y = min(y, SCREEN_DRAW_AREA_TO_Y)
	mouse.move(x - pos[0], y - pos[1])

# ----------
# Config:

ONLY_DEBUG=False  # Only show data. Don't move mouse

# Area on your display (remember to keep correct ratio (1872:1404 or 312:234) or your input will get streched/squashed!)
SCREEN_DRAW_AREA_FROM_X = -8000
SCREEN_DRAW_AREA_FROM_Y = -3000
SCREEN_DRAW_AREA_TO_X = 1872 * 1.025641025641026 * 7 -8000
SCREEN_DRAW_AREA_TO_Y = 1404 * 1.025641025641026 * 7 -3000
SCREEN_DRAW_BUTTON_PRESSURE = 55512  # Pressure needed to click the left mouse button (0 contact; 4095 = hardest)
SCALE = "STRETCH" # Either "FIT" (rM) or "STRETCH" (rM)

# ----------

WACOM_WIDTH = 15725  # Values just checked by drawing to the edges
WACOM_HEIGHT = 20967 # ↑

screenRectWidth = SCREEN_DRAW_AREA_TO_X - SCREEN_DRAW_AREA_FROM_X
screenRectHeight = SCREEN_DRAW_AREA_TO_Y - SCREEN_DRAW_AREA_FROM_Y
#ratioX = screenRectWidth / WACOM_WIDTH    # (Portrait)
#ratioY = screenRectHeight / WACOM_HEIGHT  # (Portrait)
ratioX = screenRectWidth / WACOM_HEIGHT  # (Landscape)
ratioY = screenRectHeight / WACOM_WIDTH  # (Landscape)

if SCALE == "FIT":
	ratioX = ratioY = min(ratioX, ratioY)
elif SCALE == "STRETCH":
	ratioX = ratioY = max(ratioX, ratioY)

# Source: https://github.com/canselcik/libremarkable/blob/master/src/input/wacom.rs
EV_SYNC = 0
EV_KEY = 1
EV_ABS = 3
WACOM_EVCODE_PRESSURE = 24
WACOM_EVCODE_DISTANCE = 25
WACOM_EVCODE_XTILT = 26
WACOM_EVCODE_YTILT = 27
WACOM_EVCODE_XPOS = 0
WACOM_EVCODE_YPOS = 1

lastXPos = -1
lastYPos = -1
lastXTilt = -1
lastYTilt = -1
lastDistance = -1
lastPressure = -1

mouseButtonPressed = False

# Source: https://github.com/DAA233/kalman-filter/
#stateMatrix = np.zeros((4, 1), np.float32)  # [x, y, delta_x, delta_y]
#estimateCovariance = np.eye(stateMatrix.shape[0])
#transitionMatrix = np.array([[1, 0, 1, 0],[0, 1, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1]], np.float32)
#processNoiseCov = np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]], np.float32) * 0.001
#measurementStateMatrix = np.zeros((2, 1), np.float32)
#observationMatrix = np.array([[1,0,0,0],[0,1,0,0]],np.float32)
#measurementNoiseCov = np.array([[1,0],[0,1]], np.float32) * 1
#kalman = KalmanFilter(X=stateMatrix,
#                      P=estimateCovariance,
#                      F=transitionMatrix,
#                      Q=processNoiseCov,
#                      Z=measurementStateMatrix,
#                      H=observationMatrix,
#                      R=measurementNoiseCov)

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((argv[1] if len(argv) == 2 else '10.11.99.1', 33333))

while True:
	evDevType, evDevCode, evDevValue = struct.unpack('HHi', client.recv(8))
	if evDevType == EV_ABS:
		if evDevCode == WACOM_EVCODE_XPOS:
			lastYPos = evDevValue  # X is Y (Portrait)
		elif evDevCode == WACOM_EVCODE_YPOS:
			lastXPos = evDevValue  # Y is X (Portrait)
		elif evDevCode == WACOM_EVCODE_XTILT:
			lastXTilt = evDevValue
		elif evDevCode == WACOM_EVCODE_YTILT:
			lastYTilt = evDevValue
		elif evDevCode == WACOM_EVCODE_DISTANCE:
			lastDistance = evDevValue
		elif evDevCode == WACOM_EVCODE_PRESSURE:
			if not ONLY_DEBUG:
				if not mouseButtonPressed and evDevValue > SCREEN_DRAW_BUTTON_PRESSURE:
					mouse.press(Button.left)
					mouseButtonPressed = True
				elif mouseButtonPressed and evDevValue <= SCREEN_DRAW_BUTTON_PRESSURE:
					mouse.release(Button.left)
					mouseButtonPressed = False

			lastPressure = evDevValue

		if ONLY_DEBUG:
			print('XPos: %5d | YPos: %5d | XTilt: %5d | YTilt: %5d | Distance: %3d | Pressure: %4d' % (lastXPos, lastYPos, lastXTilt, lastYTilt, lastDistance, lastPressure))
		else:
			#screenX = SCREEN_DRAW_AREA_FROM_X + round(lastXPos * ratioX)                  # (X doesn't need to invert) (Portrait)
			screenX = SCREEN_DRAW_AREA_FROM_X + round((WACOM_HEIGHT - lastYPos) * ratioX)  # (X has to be inverted) (Landscape)
			#screenY = SCREEN_DRAW_AREA_FROM_Y + round((WACOM_HEIGHT - lastYPos) * ratioY)  # (Y has to be inverted) (Portrait)
			screenY = SCREEN_DRAW_AREA_FROM_Y + round((WACOM_WIDTH - lastXPos) * ratioY)  # (Y has to be inverted) (Landscape)

			mouseMoveAbs(screenX, screenY) # Old without Kalman
			#current_measurement = np.array([[np.float32(screenX)], [np.float32(screenY)]])
			#current_prediction = kalman.predict()

			#cmx, cmy = current_measurement[0], current_measurement[1]
			#cpx, cpy = current_prediction[0], current_prediction[1]

			#kalman.correct(current_measurement)

			#mouseMoveAbs(int(np.round(cpx)), int(np.round(cpy)))

