package coin_gas_service

import (
	"bwallet/pkg/gredis"
	"bwallet/pkg/util"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

type CoinGas struct {
	Id       int
	CoinName string
	Low      float32
	Average  float32
	High     float32
}

func GetCoinGas(coin string) (float32, error) {
	gas, err := gredis.HashGet(strings.ToUpper(coin)+"_GAS", "Final", 3)
	if err != nil {
		return 0.0, err
	}
	return util.ToFloat32(string(gas)), nil

}

func (a *CoinGas) Etherscan() error {
	params := make(map[string]string)
	params["module"] = "gastracker"
	params["action"] = "gasoracle"
	params["apikey"] = "ZUT8I3GGVCSBRACCCXCTGGVCPYE8WEID6S"

	req, err := http.NewRequest(http.MethodGet, "https://api-cn.etherscan.com/api", nil)
	if err != nil {
		return err
	}
	condition := make(url.Values)
	condition.Add("module", params["module"])
	condition.Add("action", params["action"])
	condition.Add("apikey", params["apikey"])

	req.URL.RawQuery = condition.Encode()
	r, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return err
	}
	result := map[string]interface{}{}
	json.Unmarshal(body, &result)

	eth_gas, _ := result["result"].(map[string]interface{})

	gredis.HashSet("ETH_GAS", "Low", eth_gas["SafeGasPrice"], 3)
	gredis.HashSet("ETH_GAS", "Average", eth_gas["ProposeGasPrice"], 3)
	gredis.HashSet("ETH_GAS", "High", eth_gas["FastGasPrice"], 3)

	final := 21000 * util.ToFloat32(eth_gas["SafeGasPrice"]) * 0.000000001
	gredis.HashSet("ETH_GAS", "Final", final, 3)

	return nil
}

func (a *CoinGas) Btcscan() error {
	req, err := http.NewRequest(http.MethodGet, "https://btc.com/service/fees/recommended", nil)
	if err != nil {
		return err
	}

	r, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return err
	}
	result := map[string]interface{}{}
	json.Unmarshal(body, &result)

	btc_gas, _ := result["data"].(map[string]interface{})
	gredis.HashSet("BTC_GAS", "Low", btc_gas["one_block_fee"], 3)
	gredis.HashSet("BTC_GAS", "Average", btc_gas["one_block_fee"], 3)
	gredis.HashSet("BTC_GAS", "High", btc_gas["one_block_fee"], 3)

	final := util.ToFloat32(btc_gas["one_block_fee"]) * (1 + 0.1)
	gredis.HashSet("BTC_GAS", "Final", final, 3)

	return nil
}
