package base

import (
	"Server-Core/Server/Base/Log"
	"encoding/csv"
	"os"
)

type CsvTable struct {
	FileName string
	Records  []CsvRecord
	Key      string
}

type CsvRecord struct {
	Record map[string]string
}

func LoadCsvCfg(filename string) *CsvTable {
	file, err := os.Open(filename)
	if err != nil {
		log.Error("open csv fail")
		return nil
	}
	defer file.Close()

	reader := csv.NewReader(file)
	if reader == nil {
		log.Error("NewReader return nil, file")
		return nil
	}
	records, err := reader.ReadAll()
	if err != nil {
		log.Error("read csv fail")
		return nil
	}

	key := ""
	colNum := len(records[0])
	recordNum := len(records)
	var allRecords []CsvRecord
	for i := 0; i < recordNum; i++ {
		record := &CsvRecord{make(map[string]string)}
		for k := 0; k < colNum; k++ {
			record.Record[records[3][k]] = records[i][k]
			if key == "" {
				key = records[3][k]
			}
		}
		allRecords = append(allRecords, *record)
	}
	var result = &CsvTable{
		filename,
		allRecords,
		key,
	}
	return result
}
