package basic

import (
	"bytes"
	"io"
	"io/fs"
	"strings"

	"asciigoat.org/ini/parser"
)

type decoder struct {
	p   *parser.Parser
	out *Document

	queue   []*token
	current *Section
}

// Decode attempts to decode an INI-style from an [io.Reader] array into a [Document]
func Decode(r io.Reader) (*Document, error) {
	var out Document

	if r == nil {
		return nil, fs.ErrNotExist
	}

	// parser
	p := parser.NewParser(r)
	// decoder
	dec := decoder{p: p, out: &out}
	// glue
	p.OnToken = dec.OnToken
	p.OnError = dec.OnError

	// Go!
	err := p.Run()
	return &out, err
}

// DecodeBytes attempts to decode an INI-style bytes array into a [Document]
func DecodeBytes(b []byte) (*Document, error) {
	return Decode(bytes.NewReader(b))
}

// DecodeString attempts to decode an INI-style string into a [Document]
func DecodeString(s string) (*Document, error) {
	return Decode(strings.NewReader(s))
}