//go:build windows

package yu_sys

import (
	yu_math "gogs.qqck.cn/s/tools/math"
	_ "syscall"
	_ "unsafe"
)

//go:linkname SyscallN syscall.SyscallN
func SyscallN(addr Address, args ...uintptr) (r1, r2, err uintptr)

func (t Address) CallGbkToUtf8(args ...any) string {
	j_str, _, _ := t.Call(args...)
	if j_str == 0 {
		return ""
	}

	j_unicode_len, _, _ := MultiByteToWideChar.Call(936, 0, j_str, uint(yu_math.MaxUint), 0, 0)
	if j_unicode_len < 1 {
		return ""
	}
	j_unicode_len *= 2
	j_unicode := make([]byte, j_unicode_len+2) // 结尾 {0,0}
	MultiByteToWideChar.Call(936, 0, j_str, uint(yu_math.MaxUint), j_unicode, j_unicode_len)

	j_utf8_size, _, _ := WideCharToMultiByte.Call(65001, 0, j_unicode, uint(yu_math.MaxUint), 0, 0, 0, 0)
	j_utf8_size -= 1
	if j_utf8_size < 1 {
		return ""
	}
	j_utf8 := make([]byte, j_utf8_size)
	WideCharToMultiByte.Call(65001, 0, j_unicode, uint(yu_math.MaxUint), j_utf8, j_utf8_size, 0, 0)

	return string(j_utf8)
}

func (t Address) CallUnicodeToUtf8(args ...any) string {
	j_ptr, _, _ := t.Call(args...)
	if j_ptr == 0 {
		return ""
	}

	j_utf8_size, _, _ := WideCharToMultiByte.Call(65001, 0, j_ptr, uint(yu_math.MaxUint), 0, 0, 0, 0)
	j_utf8_size -= 1
	if j_utf8_size < 1 {
		return ""
	}
	j_utf8 := make([]byte, j_utf8_size)
	WideCharToMultiByte.Call(65001, 0, j_ptr, uint(yu_math.MaxUint), j_utf8, j_utf8_size, 0, 0)

	return string(j_utf8)
}

func LoadLibrary(path string) Module {
	return Module(LoadLibraryW.CallUintptr(S{Unicode, path}))
}

func (t Module) GetProcAddress(name string) Address {
	return Address(GetProcAddress.CallUintptr(uintptr(t), name+"\x00"))
}
