﻿using System;
using System.Runtime.InteropServices;
using UnityEngine;

public class KeyboardInfo : MonoBehaviour
{
	[DllImport("user32.dll")]
	static extern void keybd_event(byte bVk, byte bScan, uint dwFlags,
	UIntPtr dwExtraInfo);

	// This file simply stores data to be used when loading custom keyboards.
	// Ensure you edit these values in the Inspector, not in this script!

	// Camera dimensions - The overlay resolution displayed in VR.
	// (If you adjusted the aspect ratio of the keyboard, change these to match!)
	public int CameraPixelsWidth = 1600;
	public int CameraPixelsHeight = 600;

	// Keyboard region.
	// (UK, US, FR, JP, KR, etc.)
	// If unsure of the region name, please ask in Discord so we can keep this standardized!
	public string KeyboardRegion = "US";

	// The following GameObjects are optional, these will be automatically updated if set.
	// For example, when caps lock is enabled, the CapsLockDownKey object will be enabled, and the up key disabled.
	public GameObject[] CapsLockDownKeys = null;
	public GameObject[] CapsLockUpKeys = null;

	public GameObject[] ScrollLockDownKeys = null;
	public GameObject[] ScrollLockUpKeys = null;

	public GameObject[] NumLockDownKeys = null;
	public GameObject[] NumLockUpKeys = null;

	public GameObject[] ShiftDownKeys = null;
	public GameObject[] ShiftUpKeys = null;

	// If OVR Toolkit should automatically capitalize letters on the keyboard when pressing shift.
	public bool AutoCapitalizeLetters = true;

	/// <summary>
	/// Press a keyboard key.
	/// </summary>
	/// <param name="keyCode">The key code of the key to press.</param>
	public void KeyDown(string keyCode) {
		if (!keyCode.StartsWith("0x")) {
			return;
		}
		PressKey(keyCode, true);
	}

	/// <summary>
	/// Release a keyboard key.
	/// </summary>
	/// <param name="keyCode"></param>
	public void KeyUp(string keyCode) {
		if (!keyCode.StartsWith("0x")) {
			return;
		}
		PressKey(keyCode, false);
	}

	/// <summary>
	/// Presses or releases a keyboard key.
	/// </summary>
	/// <param name="key">The keycode of the key to press.</param>
	/// <param name="keyDown">If the key is being pressed or released.</param>
	void PressKey(string key, bool keyDown) {
		try {
			uint parsedInt = Convert.ToUInt32(key, 16);
			if (keyDown) {
				keybd_event(Convert.ToByte(parsedInt), 0, 0, (UIntPtr)0);
			}
			else {
				keybd_event(Convert.ToByte(parsedInt), 0, 0x0002, (UIntPtr)0);
			}
		}
		catch {
			Debug.Log("Couldn't parse custom keyboard keycode! Please check it is correctly named! Key name: " + key);
		}
	}
}
