package outputs

import (
	"fmt"

	"github.com/dolphindb/api-go/model"
	"github.com/influxdata/telegraf"
)

const TimeKey = "timestamp"

type TableRow []interface{}

type Serializer struct {
	TableSchema *TableSchema
}

func NewSerializer(ts *TableSchema) *Serializer {
	return &Serializer{TableSchema: ts}
}

func (sr *Serializer) Serialize(metric telegraf.Metric) (TableRow, error) {
	tr := make(TableRow, len(sr.TableSchema.ColumnMetaSet))

	for _, tag := range metric.TagList() {
		err := sr.setMetricToTableRow(tr, tag.Key, tag.Value)
		if err != nil {
			return nil, fmt.Errorf("add tag metric failed. %v", err)
		}
	}

	for _, field := range metric.FieldList() {
		err := sr.setMetricToTableRow(tr, field.Key, field.Value)
		if err != nil {
			return nil, fmt.Errorf("add field metric failed. %v", err)
		}
	}

	err := sr.setMetricToTableRow(tr, TimeKey, metric.Time())
	if err != nil {
		return nil, fmt.Errorf("add metric time failed. %v", err)
	}
	return tr, nil
}

func (sr *Serializer) setMetricToTableRow(tr TableRow, k string, v interface{}) error {
	cm, ok := sr.TableSchema.ColumnMetaSet[k]
	if ok {
		dt, err := model.NewDataType(cm.DataTypeByte, v)
		if err != nil {
			return fmt.Errorf("new datatype failed. %v", err)
		}

		tr[cm.Index] = dt
	}

	return nil
}
