package tradsetservice

import (
	"fmt"
	"go-admin/common/global"
	"go-admin/common/helper"
	"go-admin/models"

	"github.com/bytedance/sonic"
	"github.com/go-admin-team/go-admin-core/logger"
)

// 获取交易所交易对
// symbolType 1:spot 2:future
func GetExchangeTradeSets(exchange string, symbolType int) (*[]models.TradeSet, error) {
	var tradeSets []models.TradeSet
	var scanKey string

	if symbolType == 1 {
		scanKey = fmt.Sprintf(global.TICKER_SPOT, exchange, "*")
	} else if symbolType == 2 {
		scanKey = fmt.Sprintf(global.TICKER_FUTURES, exchange, "*")
	} else {
		return nil, fmt.Errorf("symbolType error")
	}

	vals, err := helper.DefaultRedis.GetAllKeysAndValues(scanKey)
	if err != nil {
		return nil, err
	}

	for _, val := range vals {
		var tradeSet models.TradeSet
		if err := sonic.Unmarshal([]byte(val), &tradeSet); err != nil {
			logger.Errorf("unmarshal tradeSet err:%v", err)
			continue
		}
		tradeSets = append(tradeSets, tradeSet)
	}

	return &tradeSets, nil
}

// 获取单个交易对
func GetExchangeTradeSet(exchange string, symbolType int, symbol string) (*models.TradeSet, error) {
	var tradeSet models.TradeSet
	var scanKey string

	if symbolType == 1 {
		scanKey = fmt.Sprintf(global.TICKER_SPOT, exchange, symbol)
	} else if symbolType == 2 {
		scanKey = fmt.Sprintf(global.TICKER_FUTURES, exchange, symbol)
	} else {
		return nil, fmt.Errorf("symbolType error")
	}

	val, err := helper.DefaultRedis.GetString(scanKey)
	if err != nil {
		return nil, err
	}

	if err := sonic.Unmarshal([]byte(val), &tradeSet); err != nil {
		logger.Errorf("unmarshal tradeSet err:%v", err)
		return nil, err
	}

	return &tradeSet, nil
}
