package mqe

import (
	"database/sql"

	"gordenko.dev/dima/qb"
)

type RawMeasure struct {
	Time  int64   `json:"t"`
	Value float64 `json:"v"`
}

type RawMeasuresFilter struct {
	MetricID   int64         `json:"metricID"`
	MetricType qb.MetricType `json:"metricType"`
	Since      int64         `json:"since"` // уже учтен firstHourOfDay
	Until      int64         `json:"until"` // уже учтен firstHourOfDay
}

// ListRawMeasures - cписок показаний мгновенных метрик (Температура, Давление, Расход)
// за за интервал без группировки
func (s *MeasureQueryEngine) ListRawMeasures(req RawMeasuresFilter) (_ []RawMeasure, err error) {
	tx, err := s.db.Driver().Begin()
	if err != nil {
		return
	}
	defer tx.Rollback()

	rows, err := tx.Query(`
	SELECT tm, value
	FROM f64
	WHERE metricID=? AND tm BETWEEN ? AND ?
	ORDER BY tm ASC`,
		req.MetricID, req.Since, req.Until)
	if err != nil {
		if err == sql.ErrNoRows {
			err = nil
		}
		return
	}
	defer rows.Close()

	var result []RawMeasure

	for rows.Next() {
		var (
			tm    int64
			value float64
		)
		err = rows.Scan(&tm, &value)
		if err != nil {
			return
		}
		result = append(result, RawMeasure{
			Time:  tm,
			Value: value,
		})
	}

	if err = rows.Err(); err != nil {
		return
	}

	if len(result) == 0 {
		return
	}

	if req.MetricType == qb.Cumulative {
		var corrections []_f64Correction
		corrections, err = listF64CorrectionsTx(tx, req.MetricID)
		if err != nil {
			return
		}

		if len(corrections) > 0 {
			applyCorrectionsToRawMeasures(corrections, result)
		}
	}
	return result, nil
}
