package otaUpgrade

import (
	"fmt"
	"github.com/gogf/gf/database/gredis"
)

const (
	FileKeyPrefix     = "ota:file:"
	ProgressKeyPrefix = "ota:progress:"
	dataExpires       = 7200
)

type File struct {
	FileId   int
	FileData []byte
}

type Progress struct {
	DeviceId string
	Progress int
}
type OtaManager struct {
	redisClient *gredis.Redis
}

func NewOtaManager(host string, port, db int) *OtaManager {
	red := gredis.New(&gredis.Config{
		Host:      host,
		Port:      port,
		Db:        db,
		MaxActive: 100,
	})
	mgr := &OtaManager{
		redisClient: red,
	}
	return mgr
}

func (mgr *OtaManager) SavaFile(id int, fileData []byte) error {
	key := fmt.Sprintf("%s%d", FileKeyPrefix, id)
	file := new(File)
	file.FileId = id
	file.FileData = fileData
	_, err := mgr.redisClient.Do("SET", key, file)
	if err != nil {
		return err
	}
	_, err = mgr.redisClient.Do("EXPIRE", key, dataExpires)
	if err != nil {
		return err
	}
	return nil
}

func (mgr *OtaManager) GetFile(id int) (*File, error) {
	key := fmt.Sprintf("%s%d", FileKeyPrefix, id)
	file := new(File)
	// get status from redis
	result, err := mgr.redisClient.DoVar("GET", key)
	if err != nil {
		return nil, err
	}
	err = result.Struct(file)
	if err != nil {
		return nil, err
	}
	return file, nil
}

func (mgr *OtaManager) DelFile(id int) error {
	key := fmt.Sprintf("%s%d", FileKeyPrefix, id)
	_, err := mgr.redisClient.Do("DEL", key)
	if err != nil {
		return err
	}

	return nil
}

func (mgr *OtaManager) GetProgress(id string) (*Progress, error) {
	key := ProgressKeyPrefix + id
	progress := new(Progress)
	result, err := mgr.redisClient.DoVar("GET", key)
	if err != nil {
		return nil, err
	}
	_, err = mgr.redisClient.Do("EXPIRE", key, dataExpires)
	if err != nil {
		return nil, err
	}
	err = result.Struct(progress)
	if err != nil {
		return nil, err
	}
	return progress, nil
}

func (mgr *OtaManager) UpdateProgress(id string, progress int) error {
	key := ProgressKeyPrefix + id
	_, err := mgr.redisClient.Do("SET", key, progress)
	if err != nil {
		return err
	}
	_, err = mgr.redisClient.Do("EXPIRE", key, dataExpires)
	if err != nil {
		return err
	}
	return nil
}

func (mgr *OtaManager) DelProgress(id string) error {
	key := ProgressKeyPrefix + id
	_, err := mgr.redisClient.Do("DEL", key)
	if err != nil {
		return err
	}

	return nil
}
