package output

import (
	"log"
	"mayhem-party/src/device/output/key"
	"time"

	"github.com/micmonay/keybd_event"
)

type Keyboard struct {
	created time.Time
	kb      *keybd_event.KeyBonding
}

func NewKeyboard() Keyboard {
	kb, err := keybd_event.NewKeyBonding()
	if err != nil {
		panic(err)
	}
	return Keyboard{
		kb:      &kb,
		created: time.Now(),
	}
}

func (kb Keyboard) wait() {
	if delta := time.Since(kb.created.Add(time.Second * 2)); delta < 0 {
		time.Sleep(-1 * delta)
	}
}

func (kb Keyboard) Press(keys ...key.Key) {
	kb.wait()

	kb.release()
	if len(keys) == 0 {
		return
	}

	ints := make([]int, len(keys))
	for i := range keys {
		ints[i] = int(keys[i])
	}

	kb.kb.SetKeys(ints...)
	if err := kb.kb.Press(); err != nil {
		log.Println("failed to press keys:", err)
	}
}

func (kb Keyboard) Close() {
	kb.release()
}

func (kb Keyboard) release() {
	kb.wait()

	if err := kb.kb.Release(); err != nil {
		log.Println("failed to release keys:", err)
	}
}
