package data

import (
	"bytes"
	"errors"

	"code.ur.gs/lupine/ordoor/internal/util/asciiscan"
)

// Comments are `//`, start of line only, for accounting
var (
	comment = []byte("//")
)

type Accounting map[string]string

func LoadAccounting(filename string) (Accounting, error) {
	s, err := asciiscan.New(filename)
	if err != nil {
		return nil, err
	}

	defer s.Close()
	scanLines := s.Bufio()

	out := make(Accounting)

	for scanLines.Scan() {
		if err := parse(out, scanLines.Bytes()); err != nil {
			return nil, err
		}
	}

	if err := scanLines.Err(); err != nil {
		return nil, err
	}

	return out, nil
}

func parse(into Accounting, line []byte) error {
	if len(line) == 0 || bytes.Equal(line[0:2], comment) {
		return nil
	}

	idx := bytes.Index(line, []byte("="))
	key := string(line[0:idx])
	value := string(bytes.Trim(line[idx+1:len(line)], "\t\r\n"))

	if _, ok := into[key]; ok {
		return errors.New("Duplicate key: " + key)
	}

	into[key] = value

	return nil
}
