package src

import (
	"context"
	"mayhem-party/src/device/input"
	"mayhem-party/src/device/output"
	"mayhem-party/src/device/output/key"
	"os"
	"time"
)

func Main(ctx context.Context) error {
	reader := input.New(ctx)
	writer := output.New(ctx)
	defer writer.Close()
	defer reader.Close()

	interval := time.Millisecond * 50
	if intervalS, ok := os.LookupEnv("MAIN_INTERVAL_DURATION"); !ok {
	} else if v, err := time.ParseDuration(intervalS); err != nil {
		panic(err)
	} else {
		interval = v
	}
	c := time.NewTicker(interval)
	defer c.Stop()

	block := func() bool {
		select {
		case <-c.C:
			return true
		case <-ctx.Done():
			return false
		}
	}

	state := map[key.Key]bool{}
	for block() {
		delta := reader.Read()
		for _, button := range delta {
			state[key.FromChar(button.Char)] = button.Down
		}
		keys := make([]key.Key, 0)
		for k, v := range state {
			if v {
				keys = append(keys, k)
			}
		}
		writer.Press(keys...)
	}

	return ctx.Err()
}
