package handler

import (
	"encoding/json"
	"net/http"
	"time"

	"go_rain_dtu/internal/dao"
	"go_rain_dtu/pkg/logger"
)

type SensorHandler struct {
	dao *dao.SensorDAO
}

func NewSensorHandler(dao *dao.SensorDAO) *SensorHandler {
	return &SensorHandler{dao: dao}
}

func (h *SensorHandler) GetAggregatedData(w http.ResponseWriter, r *http.Request) {
	interval := r.URL.Query().Get("interval")
	if interval == "" {
		interval = "1hour"
	}

	endTime := time.Now()
	startTime := endTime.Add(-24 * time.Hour) // 默认显示24小时数据

	if startStr := r.URL.Query().Get("start"); startStr != "" {
		if t, err := time.Parse("2006-01-02T15:04", startStr); err == nil {
			startTime = t
		}
	}
	if endStr := r.URL.Query().Get("end"); endStr != "" {
		if t, err := time.Parse("2006-01-02T15:04", endStr); err == nil {
			endTime = t
		}
	}

	data, err := h.dao.GetAggregatedData(startTime, endTime, interval)
	if err != nil {
		logger.Logger.Printf("获取聚合数据失败: %v", err)
		http.Error(w, "服务器内部错误", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	// 使用自定义的编码器，设置时间格式
	encoder := json.NewEncoder(w)
	encoder.SetIndent("", "  ")
	if err := encoder.Encode(data); err != nil {
		logger.Logger.Printf("JSON编码失败: %v", err)
		http.Error(w, "服务器内部错误", http.StatusInternalServerError)
		return
	}
}

// 处理静态文件
func (h *SensorHandler) ServeStatic(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path == "/" {
		http.ServeFile(w, r, "static/index.html")
		return
	}
	http.FileServer(http.Dir("static")).ServeHTTP(w, r)
}
