package input

import (
	"os"

	"github.com/go-yaml/yaml"
)

type Remap struct {
	input Input
	m     map[byte]byte
}

func NewRemapFromFile(input Input, p string) Remap {
	b, err := os.ReadFile(p)
	if err != nil {
		panic(err)
	}
	var m map[string]string
	if err := yaml.Unmarshal(b, &m); err != nil {
		panic(err)
	}
	remap := map[byte]byte{}
	for k, v := range m {
		if len(k) != 1 || len(v) != 1 {
			panic("remap must be char:char")
		}
		remap[k[0]] = v[0]
	}
	return NewRemap(input, remap)
}

func NewRemap(input Input, m map[byte]byte) Remap {
	return Remap{
		input: input,
		m:     m,
	}
}

func (re Remap) Close() {
	re.input.Close()
}

func (re Remap) Read() []Button {
	result := re.input.Read()
	for i := range result {
		if v, ok := re.m[result[i].Char]; ok {
			result[i].Char = v
		}
	}
	return result
}
