package macro;

//import static macro.EnumerateWindows.User32DLL.GetAllWindows;
import static macro.EnumerateWindows.User32DLL.SendMessageA;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;

import com.sun.jna.platform.DesktopWindow;
import com.sun.jna.platform.WindowUtils;
import com.sun.jna.platform.win32.WinDef.LPARAM;
import com.sun.jna.platform.win32.WinDef.WPARAM;
import com.sun.jna.platform.win32.WinUser;
import static com.sun.jna.Native.getLastError;;

public class Input {

	public static void press(char c, int timeInMs) {
		Robot robot;
		try {
			robot = new Robot();
			robot.keyPress(KeyEvent.getExtendedKeyCodeForChar(c));
			robot.delay(timeInMs);
			robot.keyRelease(KeyEvent.getExtendedKeyCodeForChar(c));
		} catch (AWTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void press(char c) {
		Robot robot;
		try {
			robot = new Robot();
			robot.keyPress(KeyEvent.getExtendedKeyCodeForChar(c));
			robot.delay(100);
			robot.keyRelease(KeyEvent.getExtendedKeyCodeForChar(c));
		} catch (AWTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void press(char c, int timeInMs, String windowName) {
		DesktopWindow window = WindowUtils.getAllWindows(true).stream()
				.filter(w -> w.getTitle().toLowerCase().contains(windowName.toLowerCase())).findFirst().get();
		SendMessageA(window.getHWND(), WinUser.WM_KEYDOWN, new WPARAM(c), new LPARAM(0));
		System.out.println(getLastError());
		try {
			Thread.sleep(timeInMs);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		SendMessageA(window.getHWND(), WinUser.WM_KEYUP, new WPARAM(c), new LPARAM(0));
	}

	public static void press(char c, String windowName) {
		DesktopWindow window = WindowUtils.getAllWindows(true).stream()
				.filter(w -> w.getTitle().toLowerCase().contains(windowName.toLowerCase())).findFirst().get();

		SendMessageA(window.getHWND(), WinUser.WM_KEYDOWN, new WPARAM(c), new LPARAM(0));
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		SendMessageA(window.getHWND(), WinUser.WM_KEYUP, new WPARAM(c), new LPARAM(0));
	}
}
