package coin_ticker_service

import (
	"bwallet/models"
)

type CoinTicker struct {
	Id         int
	CoinId     int
	CoinName   string
	Ticker     string
	PlatformId int
}

type CoinTickerResp struct {
	Id         int    `json:"id"`
	CoinName   string `json:"coin_name"`
	CoinId     int    `json:"coin_id"`
	CoinTicker string `json:"coin_ticker"`
	Icon       string `json:"icon"`
	Platform   string `json:"platform"`
	Chain      string `json:"chain"`
}

func (ct *CoinTicker) GetAll() ([]*CoinTickerResp, error) {
	coins_ticker, err := models.GetCoinsTicker(ct.getMaps())
	if err != nil {
		return nil, err
	}

	var coinsResp = []*CoinTickerResp{}
	for _, val := range coins_ticker {
		tmp := &CoinTickerResp{}
		tmp.Id = val.ID
		tmp.CoinName = val.CoinInfo.Name
		tmp.CoinId = val.CoinId
		tmp.CoinTicker = val.Ticker
		tmp.Icon = val.CoinInfo.Icon
		tmp.Platform = val.CoinInfo.Platform
		tmp.Chain = val.CoinInfo.Chain
		coinsResp = append(coinsResp, tmp)
	}

	return coinsResp, nil
}

func (t *CoinTicker) Add() error {
	coinTicker := map[string]interface{}{
		"coin_name":   t.CoinName,
		"coin_id":     t.CoinId,
		"ticker":      t.Ticker,
		"platform_id": t.PlatformId,
	}

	if err := models.AddCoinTicker(coinTicker); err != nil {
		return err
	}

	return nil
}

func (t *CoinTicker) Edit() error {
	return models.EditCoinTicker(t.getMaps(), map[string]interface{}{
		"ticker": t.Ticker,
	})
}

func (t *CoinTicker) Exist() (bool, error) {
	return models.ExistCoin(t.CoinName, t.PlatformId)
}

func (t *CoinTicker) ExistById() (bool, error) {
	return models.ExistById(t.Id)
}

func (t *CoinTicker) GetCoinTicker() (*models.CoinTicker, error) {
	ticker, err := models.GetCoinTicker(t.Id)
	if err != nil {
		return nil, err
	}

	return ticker, nil
}

func (t *CoinTicker) Delete() error {
	return models.DeleteCoinTicker(t.Id)
}

func (c *CoinTicker) getMaps() (map[string]interface{}) {
	maps := make(map[string]interface{})

	if c.CoinName != "" {
		maps["coin_name"] = c.CoinName
	}

	if c.PlatformId != 0 {
		maps["platform_id"] = c.PlatformId
	}
	return maps
}
