//go:build windows

package yu_curl

import (
	yu_fast "gogs.qqck.cn/s/tools/fast"
	yu_http "gogs.qqck.cn/s/tools/http"
	yu_strings "gogs.qqck.cn/s/tools/strings"
	"strings"
	"syscall"
	"unsafe"
)

var callback_PREREQFUNCTION_ptr = syscall.NewCallbackCDecl(func(userdata, conn_primary_ip, conn_local_ip, conn_primary_port, conn_local_port uintptr) uintptr {
	t := (*Request)(unsafe.Pointer(userdata))
	t.resp_reset()
	return PREREQFUNC_OK
})

var callback_WRITEFUNCTION_ptr = syscall.NewCallbackCDecl(func(buffer uintptr, size uintptr, nmemb uintptr, userdata uintptr) uintptr {
	t := (*Request)(unsafe.Pointer(userdata))
	t.resp_body = append(t.resp_body, yu_fast.P2B(buffer, size*nmemb)...)
	return size * nmemb
})

var callback_HEADERFUNCTION_ptr = syscall.NewCallbackCDecl(func(bheader uintptr, size uintptr, nitems uintptr, userdata uintptr) uintptr {
	t := (*Request)(unsafe.Pointer(userdata))
	j_headers := yu_strings.GbkPtrLenToUtf8(bheader, size*nitems)
	t.resp_headers_raw = append(t.resp_headers_raw, j_headers...)
	if strings.HasSuffix(j_headers, "\r\n") {
		j_headers = j_headers[:len(j_headers)-2]
	}
	if strings.HasSuffix(j_headers, "\n") {
		j_headers = j_headers[:len(j_headers)-1]
	}
	if j_headers == "" {
		return size * nitems
	}
	j_key, j_value := yu_strings.Left(j_headers, ":"), yu_strings.Empty(yu_strings.Right(j_headers, ":"))
	if j_key != "" && j_value != "" {
		j_key = yu_http.Normalize(j_key)
		if j_key == "Set-Cookie" {
			if strings.Index(j_value, ";") > -1 {
				j_value = yu_strings.Left(j_value, ";")
			}
			if strings.Index(j_value, "=") == -1 {
				return size * nitems
			}
			j_key, j_value = yu_strings.Left(j_value, "="), yu_strings.Empty(yu_strings.Right(j_value, "="))
			if j_value == "" {
				delete(t.resp_cookies, j_key)
			} else {
				t.resp_cookies[j_key] = j_value
			}
			if t.cookies_updata {
				t.SetCookie(j_key, j_value)
			}
		} else {
			t.resp_headers[j_key] = j_value
		}
	}
	return size * nitems
})
