package executor

import (
	"github.com/go-redis/redis"
	"strconv"
)

const (
	KHTaskPool = "rt:task_pool"
)

type IPoolLoader interface {
	LoadTo(*TaskPool) error
	Serialize(*TaskPool) error
}

type PoolRedisLoader struct {
	h *redis.Client
}

func NewPoolRedisLoader(r *redis.Client) IPoolLoader{
	return &PoolRedisLoader{h:r}
}

func (self *PoolRedisLoader) LoadTo(pool *TaskPool) error {
	var err error = nil

	mss, err := self.h.HGetAll(KHTaskPool).Result()
	if err != nil {
		return err
	}

	for _, js := range mss {
		t, err := NewTaskFromJson(js)
		if err != nil {
			break
		}
		err = pool.AddTask(t)
		if nil != err {
			break
		}
	}
	return err
}

func (self *PoolRedisLoader) Serialize(pool *TaskPool) error {
	var last_error error = nil

	fields := make(map[string]interface{})
	for id, task := range pool.tasks {
		js, err := task.ToJson()
		if nil != err {
			last_error = err
			continue
		}
		fields[strconv.FormatInt(id, 10)] = string(js)
	}
	_, err := self.h.HMSet(KHTaskPool, fields).Result()
	if err != nil {
		last_error = err
	}
	return last_error
}