package res_c

import (
	"context"
	"git.hilo.cn/hilo-common/domain"
	"hilo-group/_const/redis_key"
	"hilo-group/domain/model/res_m"
	"time"
)

func GetCountryIconMap(model *domain.Model) (map[string]string, error) {
	m, err := GetAllCountryIcon(model)
	if err != nil || len(m) <= 0 {
		m, err = res_m.GetAllCountries(model)
		if err != nil {
			return nil, err
		}
		if len(m) <= 0 {
			return map[string]string{}, nil
		}
		SaveAllCountryIcon(model, m)
	}
	return m, nil
}

func GetAllCountryIcon(model *domain.Model) (map[string]string, error) {
	key := redis_key.GetCountryIconKey()
	return model.Redis.HGetAll(context.Background(), key).Result()
}

func SaveAllCountryIcon(model *domain.Model, icons map[string]string) (int64, error) {
	key := redis_key.GetCountryIconKey()
	ret, err := model.Redis.HSet(context.Background(), key, icons).Result()
	if err == nil {
		model.Redis.Expire(context.Background(), key, time.Minute*10)
	}
	return ret, err
}

func GetCountryAreaMap(model *domain.Model) (map[string]string, error) {
	m, err := GetAllCountryArea(model)
	if err != nil || len(m) <= 0 {
		m, err = res_m.GetAllCountriesArea(model)
		if err != nil {
			return nil, err
		}
		if len(m) <= 0 {
			return map[string]string{}, nil
		}
		SaveAllCountryArea(model, m)
	}
	return m, nil
}

func GetAllCountryArea(model *domain.Model) (map[string]string, error) {
	key := redis_key.GetCountryAreaKey()
	return model.Redis.HGetAll(context.Background(), key).Result()
}

func SaveAllCountryArea(model *domain.Model, data map[string]string) (int64, error) {
	key := redis_key.GetCountryAreaKey()
	ret, err := model.Redis.HSet(context.Background(), key, data).Result()
	if err == nil {
		model.Redis.Expire(context.Background(), key, time.Minute*10)
	}
	return ret, err
}