// +build windows

package drop

import (
	"unsafe"

	"golang.org/x/text/encoding/unicode"
	"opslag.de/schobers/geom"
	"opslag.de/schobers/zntg/ui"
)

/*
#include <Windows.h>
#include <stdint.h>

void SetDragAndDropHook(void* window);
*/
import "C"

type handler struct {
	Target ui.DragDropEventTarget
	Files  []string
}

var targets map[ui.DragDropEventTarget]struct{} = map[ui.DragDropEventTarget]struct{}{}
var droppedFiles []string

//export clearDrop
func clearDrop() {
	droppedFiles = nil
}

//export dropFinished
func dropFinished(x, y C.INT) {
	for target := range targets {
		target.Drop(geom.PtF32(float32(x), float32(y)), droppedFiles)
	}
}

//export addDroppedFile
func addDroppedFile(filePath *C.wchar_t, filePathLength C.UINT) {
	pathBytes := C.GoBytes(unsafe.Pointer(filePath), C.int(filePathLength)*C.sizeof_wchar_t)
	decoder := unicode.UTF16(unicode.LittleEndian, unicode.UseBOM).NewDecoder()
	path, err := decoder.Bytes(pathBytes)
	if err != nil {
		return
	}
	droppedFiles = append(droppedFiles, string(path))
}

func RegisterAsDefaultProvider() {
	ui.DefaultDragDropProvider = &provider{}
}

type provider struct{}

func (p provider) Register(windowHandle uintptr, target ui.DragDropEventTarget) {
	C.SetDragAndDropHook(unsafe.Pointer(windowHandle))
	targets[target] = struct{}{}
}

func init() {
	ui.DefaultDragDropProvider = provider{}
}