package win32api

import (
	"errors"
	"syscall"
	"unsafe"
)

func WTSGetActiveConsoleSessionId() (DWORD, error) {
	kernel32, err := syscall.LoadLibrary("kernel32.dll")
	if err != nil {
		return 0, errors.New("Can't Load Kernel32 API")
	}
	defer syscall.FreeLibrary(kernel32)
	WTGet, err := syscall.GetProcAddress(syscall.Handle(kernel32), "WTSGetActiveConsoleSessionId")
	if err != nil {
		return 0, errors.New("Can't Load WTSGetActiveConsoleSessionId API")
	}
	res, _, _ := syscall.Syscall(uintptr(WTGet), 0, 0, 0, 0)
	return DWORD(res), nil
}

func CloseHandle(hObject HANDLE) error {
	kernel32, err := syscall.LoadLibrary("kernel32.dll")
	if err != nil {
		return errors.New("Can't Load Kernel32 API")
	}
	defer syscall.FreeLibrary(kernel32)
	CH, err := syscall.GetProcAddress(syscall.Handle(kernel32), "CloseHandle")
	if err != nil {
		return errors.New("Can't Load CloseHandle API")
	}
	if r, _, errno := syscall.Syscall(uintptr(CH), 1, uintptr(hObject), 0, 0); r == 0 {
		return error(errno)
	}
	return nil
}

func CreateToolhelp32Snapshot(dwFlags, th32ProcessID DWORD) (HANDLE, error) {
	kernel32, err := syscall.LoadLibrary("kernel32.dll")
	if err != nil {
		return 0, errors.New("Can't Load Kernel32 API")
	}
	defer syscall.FreeLibrary(kernel32)
	CTS, err := syscall.GetProcAddress(syscall.Handle(kernel32), "CreateToolhelp32Snapshot")
	if err != nil {
		return 0, errors.New("Can't Load CreateToolhelp32Snapshot API")
	}
	r, _, errno := syscall.Syscall(uintptr(CTS), 2, uintptr(dwFlags), uintptr(th32ProcessID), 0)
	if int(r) == -1 {
		return 0, error(errno)
	}
	return HANDLE(r), nil
}

func Process32Next(hSnapshot HANDLE, lppe *PROCESSENTRY32) error {
	kernel32, err := syscall.LoadLibrary("kernel32.dll")
	if err != nil {
		return errors.New("Can't Load Kernel32 API")
	}
	defer syscall.FreeLibrary(kernel32)
	PN, err := syscall.GetProcAddress(syscall.Handle(kernel32), "Process32Next")
	if err != nil {
		return errors.New("Can't Load Process32Next API")
	}
	r, _, errno := syscall.Syscall(uintptr(PN), 2, uintptr(hSnapshot), uintptr(unsafe.Pointer(lppe)), 0)
	if r == 0 {
		if errno != 0 {
			return error(errno)
		}
		return syscall.EINVAL
	}
	return nil
}

func GetProcessId(Process HANDLE) uint32 {
	kernel32, err := syscall.LoadLibrary("kernel32.dll")
	if err != nil {
		return 0
	}
	defer syscall.FreeLibrary(kernel32)
	GPI, err := syscall.GetProcAddress(syscall.Handle(kernel32), "GetProcessId")
	if err != nil {
		return 0
	}
	r, _, _ := syscall.Syscall(uintptr(GPI), 1, uintptr(Process), 0, 0)
	return uint32(r)
}

func GetTickCount() (uint32, error) {
	kernel32, err := syscall.LoadLibrary("kernel32.dll")
	if err != nil {
		return 0, err
	}
	defer syscall.FreeLibrary(kernel32)
	GTC, err := syscall.GetProcAddress(syscall.Handle(kernel32), "GetTickCount")
	if err != nil {
		return 0, err
	}
	r, _, _ := syscall.Syscall(uintptr(GTC), 0, 0, 0, 0)
	return uint32(r), nil
}

func GlobalMemoryStatusEx(data *MEMORYSTATUSEX) (bool, error) {
	(*data).DwLength = DWORD(unsafe.Sizeof(*data))
	kernel32, err := syscall.LoadLibrary("kernel32.dll")
	if err != nil {
		return false, err
	}
	defer syscall.FreeLibrary(kernel32)
	GMS, err := syscall.GetProcAddress(syscall.Handle(kernel32), "GlobalMemoryStatusEx")
	if err != nil {
		return false, err
	}
	r, _, errno := syscall.Syscall(uintptr(GMS), 1, uintptr(unsafe.Pointer(data)), 0, 0)
	if r == 0 {
		if errno != 0 {
			return false, error(errno)
		}
		return false, syscall.EINVAL
	}
	return true, nil
}

func LockFileEx(hFile HANDLE, dwFlags DWORD, dwReserved DWORD, nNumberOfBytesToLockLow DWORD,
	nNumberOfBytesToLockHigh DWORD, lpOverlapped *syscall.Overlapped) (bool, error) {
	kernel32, err := syscall.LoadLibrary("kernel32.dll")
	if err != nil {
		return false, err
	}
	defer syscall.FreeLibrary(kernel32)
	Lck, err := syscall.GetProcAddress(syscall.Handle(kernel32), "LockFileEx")
	if err != nil {
		return false, err
	}
	r, _, errno := syscall.Syscall6(uintptr(Lck), 6, uintptr(hFile), uintptr(dwFlags), uintptr(dwReserved),
		uintptr(nNumberOfBytesToLockLow), uintptr(nNumberOfBytesToLockHigh), uintptr(unsafe.Pointer(lpOverlapped)))
	if r == 0 {
		if errno != 0 {
			return false, error(errno)
		}
		return false, syscall.EINVAL
	}
	return true, nil
}

func OpenFileById(hVolumeHint HANDLE, lpFileId *FILE_ID_DESCRIPTOR, dwDesiredAccess DWORD, dwShareMode DWORD,
	lpSecurityAttributes *syscall.SecurityAttributes, dwFlagsAndAttributes DWORD) (HANDLE, error) {
	kernel32, err := syscall.LoadLibrary("kernel32.dll")
	if err != nil {
		return 0, err
	}
	defer syscall.FreeLibrary(kernel32)
	ofb, err := syscall.GetProcAddress(syscall.Handle(kernel32), "OpenFileById")
	if err != nil {
		return 0, err
	}
	r, _, errno := syscall.Syscall6(ofb, 6, uintptr(hVolumeHint),
		uintptr(unsafe.Pointer(lpFileId)), uintptr(dwDesiredAccess), uintptr(dwShareMode),
		uintptr(unsafe.Pointer(lpSecurityAttributes)), uintptr(dwFlagsAndAttributes))
	if r == syscall.INVALID_FILE_ATTRIBUTES {
		if errno != 0 {
			return HANDLE(r), error(errno)
		}
		return HANDLE(r), syscall.EINVAL
	}
	return HANDLE(r), nil
}

func CreateEventW(lpEventAttributes *syscall.SecurityAttributes, bManualReset bool,
	bInitialState bool, lpName LPCWSTR) (HANDLE, error) {
	var intBManualReset, intBInitialState int
	if bManualReset {
		intBManualReset = 1
	}
	if bInitialState {
		intBInitialState = 1
	}
	kernel32, err := syscall.LoadLibrary("kernel32.dll")
	if err != nil {
		return 0, err
	}
	defer syscall.FreeLibrary(kernel32)
	Lck, err := syscall.GetProcAddress(syscall.Handle(kernel32), "CreateEventW")
	if err != nil {
		return 0, err
	}
	r, _, errno := syscall.Syscall6(uintptr(Lck), 4, uintptr(unsafe.Pointer(lpEventAttributes)),
		uintptr(intBManualReset), uintptr(intBInitialState), uintptr(unsafe.Pointer(lpName)), 0, 0)
	if HANDLE(r) == 0 {
		if errno != 0 {
			return HANDLE(r), error(errno)
		}
		return HANDLE(r), syscall.EINVAL
	}
	return HANDLE(r), nil
}

func GetLogicalDriveStringsW(nBufferLength DWORD, lpBuffer LPWSTR) error {
	kernel32, err := syscall.LoadLibrary("kernel32.dll")
	if err != nil {
		return err
	}
	defer syscall.FreeLibrary(kernel32)
	glds, err := syscall.GetProcAddress(syscall.Handle(kernel32), "GetLogicalDriveStringsW")
	if err != nil {
		return err
	}
	_, _, errno := syscall.Syscall(uintptr(glds), 2, uintptr(nBufferLength), uintptr(unsafe.Pointer(lpBuffer)), 0)
	if errno != 0 {
		return error(errno)
	}
	return nil
}

func GetVolumeInformationW(lpRootPathName LPCWSTR, lpVolumeNameBuffer LPWSTR, nVolumeNameSize DWORD,
	lpVolumeSerialNumber LPDWORD, lpMaximumComponentLength LPDWORD, lpFileSystemFlags LPDWORD,
	lpFileSystemNameBuffer LPWSTR, nFileSystemNameSize DWORD) error {
	kernel32, err := syscall.LoadLibrary("kernel32.dll")
	if err != nil {
		return err
	}
	defer syscall.FreeLibrary(kernel32)
	glds, err := syscall.GetProcAddress(syscall.Handle(kernel32), "GetVolumeInformationW")
	if err != nil {
		return err
	}
	_, _, errno := syscall.Syscall9(uintptr(glds), 8, uintptr(unsafe.Pointer(lpRootPathName)),
		uintptr(unsafe.Pointer(lpVolumeNameBuffer)), uintptr(nVolumeNameSize), uintptr(unsafe.Pointer(lpVolumeSerialNumber)),
		uintptr(unsafe.Pointer(lpMaximumComponentLength)), uintptr(unsafe.Pointer(lpFileSystemFlags)),
		uintptr(unsafe.Pointer(lpFileSystemNameBuffer)), uintptr(nFileSystemNameSize), 0)
	if errno != 0 {
		return error(errno)
	}
	return nil
}

func DeviceIoControl(hDevice HANDLE, dwIoControlCode DWORD, lpInBuffer LPVOID, nInBufferSize DWORD, lpOutBuffer LPVOID,
	nOutBufferSize DWORD, lpBytesReturned LPDWORD, lpOverlapped *syscall.Overlapped) (bool, error) {
	kernel32, err := syscall.LoadLibrary("kernel32.dll")
	if err != nil {
		return false, err
	}
	defer syscall.FreeLibrary(kernel32)
	dic, err := syscall.GetProcAddress(syscall.Handle(kernel32), "DeviceIoControl")
	if err != nil {
		return false, err
	}
	r, _, errno := syscall.Syscall9(uintptr(dic), 8, uintptr(hDevice), uintptr(dwIoControlCode),
		uintptr(unsafe.Pointer(lpInBuffer)), uintptr(nInBufferSize), uintptr(unsafe.Pointer(lpOutBuffer)), uintptr(nOutBufferSize),
		uintptr(unsafe.Pointer(lpBytesReturned)), uintptr(unsafe.Pointer(lpOverlapped)), 0)
	if r == 0 {
		if errno != 0 {
			return false, error(errno)
		} else {
			return false, syscall.EINVAL
		}
	}
	return true, nil
}

func DeviceIoControlPtr(hDevice HANDLE, dwIoControlCode DWORD, lpInBuffer uintptr, nInBufferSize DWORD, lpOutBuffer uintptr,
	nOutBufferSize DWORD, lpBytesReturned LPDWORD, lpOverlapped *syscall.Overlapped) (bool, error) {
	kernel32, err := syscall.LoadLibrary("kernel32.dll")
	if err != nil {
		return false, err
	}
	defer syscall.FreeLibrary(kernel32)
	dic, err := syscall.GetProcAddress(syscall.Handle(kernel32), "DeviceIoControl")
	if err != nil {
		return false, err
	}
	r, _, errno := syscall.Syscall9(uintptr(dic), 8, uintptr(hDevice), uintptr(dwIoControlCode),
		lpInBuffer, uintptr(nInBufferSize), lpOutBuffer, uintptr(nOutBufferSize),
		uintptr(unsafe.Pointer(lpBytesReturned)), uintptr(unsafe.Pointer(lpOverlapped)), 0)
	if r == 0 {
		if errno != 0 {
			return false, error(errno)
		} else {
			return false, syscall.EINVAL
		}
	}
	return true, nil
}
