package win32api

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

func WTSQueryUserToken(SessionId HANDLE, phToken *HANDLE) error {
	wtsapi32, err := syscall.LoadLibrary("wtsapi32.dll")
	if err != nil {
		return errors.New("Can't Load Wtsapi32 API")
	}
	defer syscall.FreeLibrary(wtsapi32)
	WTGet, err := syscall.GetProcAddress(syscall.Handle(wtsapi32), "WTSQueryUserToken")
	if err != nil {
		return errors.New("Can't Load WTSQueryUserToken API")
	}
	r, _, errno := syscall.Syscall(uintptr(WTGet), 2, uintptr(SessionId), uintptr(unsafe.Pointer(phToken)), 0)
	if r == 0 {
		return error(errno)
	} else {
		return nil
	}
}

func WTSEnumerateSessions(hServer HANDLE, Reserved, Version DWORD, ppSessionInfo *HANDLE, pCount *int) error {
	wtsapi32, err := syscall.LoadLibrary("wtsapi32.dll")
	if err != nil {
		return errors.New("Can't Load Wtsapi32 API")
	}
	defer syscall.FreeLibrary(wtsapi32)
	WT, err := syscall.GetProcAddress(syscall.Handle(wtsapi32), "WTSEnumerateSessionsW")
	if err != nil {
		return errors.New("Can't Load WTSQueryUserToken API")
	}
	r, _, errno := syscall.Syscall6(uintptr(WT), 5, uintptr(hServer), uintptr(Reserved), uintptr(Version), uintptr(unsafe.Pointer(ppSessionInfo)), uintptr(unsafe.Pointer(pCount)), 0)
	if r == 0 {
		return error(errno)
	}
	return nil
}
