package edt

import (
	"encoding/csv"
	"strings"
)

type EDT struct {
	records []map[string]interface{}
}

func NewImporter(data string, fields map[string]string) (*EDT, error) {
	reader := csv.NewReader(strings.NewReader(string(data)))
	csvData, err := reader.ReadAll()
	if err != nil {
		return nil, err
	}

	csvFields := csvData[0][:]

	edt := &EDT{}
	edt.records = make([]map[string]interface{}, 0)

	n := len(csvData)
	for i := 1; i < n; i++ {
		record := make(map[string]interface{}, 0)
		for pos, value := range csvData[i] {
			if field := fields[csvFields[pos]]; field != "" {
				record[field] = value
			} else {
				field := csvFields[pos]
				record[field] = value
			}
		}
		edt.records = append(edt.records, record)
	}
	return edt, nil
}

func (edt *EDT) Records() []map[string]interface{} {
	return edt.records
}
