package service

import (
	"encoding/json"
	"fmt"
	"iot_manager_service/app/data/dao"
	"iot_manager_service/app/data/model"
	"iot_manager_service/util/cache"
	"iot_manager_service/util/common"
)

var GarbageDataService = new(garbageDataService)

type garbageDataService struct{}

func (s *garbageDataService) BatchSave(details []model.GarbageDataDetail) *common.Errors {
	garbage := &dao.GarbageData{DeviceId: ""}
	var data []dao.GarbageData
	for _, detail := range details {
		garbageData := dao.GarbageData{
			DeviceId:            detail.DeviceId,
			StartTime:           detail.StartTime,
			EndTime:             detail.EndTime,
			PostTime:            detail.PostTime,
			BatteryVoltage:      detail.BatteryVoltage,
			BatteryPercentage:   detail.BatteryPercentage,
			SensorCount:         detail.SensorCount,
			SensorOne:           detail.SensorOne,
			SensorTwo:           detail.SensorTwo,
			SensorOnePercentage: detail.SensorOnePercentage,
			SensorTwoPercentage: detail.SensorTwoPercentage,
			WorkTime:            detail.WorkTime,
		}
		b, _ := json.Marshal(&garbageData)
		cache.Redis.Set(fmt.Sprintf(model.GarbageDataKey, detail.DeviceId), string(b), 0)
		data = append(data, garbageData)
	}
	if len(data) == 0 {
		return nil
	}

	err := garbage.BatchSave(data)
	if err != nil {
		return common.FailResponse(err.Error(), nil)
	}
	return nil
}

func (s *garbageDataService) Get(deviceId string) *dao.GarbageData {
	var garbageData dao.GarbageData
	result, err := cache.Redis.Get(fmt.Sprintf(model.GarbageDataKey, deviceId)).Result()
	if err == nil {
		err = json.Unmarshal([]byte(result), &garbageData)
		if err != nil {
			return nil
		}
		return &garbageData
	}

	garbageData = dao.GarbageData{
		DeviceId: deviceId,
	}
	_ = garbageData.Get()
	return &garbageData
}
