package storage

import (
	"encoding/binary"
	"fmt"
)

func GetUsedDuration(deviceId string) (uint64, error) {
	if len(deviceId) == 0 {
		return 0, nil
	}
	key := generateDeviceIdUsedKey(deviceId)
	value, err := get(key)
	if err != nil {
		return 0, nil
	}
	data := binary.BigEndian.Uint64(value)
	return data, nil
}

func AddUsedDuration(deviceId string, duration uint64) (uint64, error) {
	if len(deviceId) == 0 {
		return 0, nil
	}
	existed, err := GetUsedDuration(deviceId)
	if err != nil {
		return 0, err
	}
	ret := existed + duration
	data := make([]byte, 8)
	binary.BigEndian.PutUint64(data, ret)
	if err := set(generateDeviceIdUsedKey(deviceId), data); err != nil {
		return 0, err
	}
	return ret, nil
}

func generateDeviceIdUsedKey(deviceId string) string {
	return fmt.Sprintf("device:%s:used", deviceId)
}
