package supported_chain_service

import (
	"bwallet/models"
)

type SupportedChain struct {
	ID         int
	PlatformId int
	CoinId     int

	PageNum  int
	PageSize int
}

type SupportedChainResp struct {
	ID       int    `json:"id"`
	Name     string `json:"name"`
	CoinId   int    `json:"coin_id"`
	Icon     string `json:"icon"`
	Platform string `json:"platform"`
	Chain    string `json:"chain"`
}

func (c *SupportedChain) Get() (*models.SupportedChain, error) {
	chain, err := models.GetSupportedChain(c.ID)
	if err != nil {
		return nil, err
	}

	return chain, nil
}

func (c *SupportedChain) GetAll() ([]*SupportedChainResp, error) {
	chains, err := models.GetSupportedChains(c.PageNum, c.PageSize, c.getMaps())
	if err != nil {
		return nil, err
	}

	var coinsResp = []*SupportedChainResp{}
	for _, val := range chains {
		tmp := &SupportedChainResp{}
		tmp.ID = val.ID
		tmp.Name = val.CoinInfo.Name
		tmp.CoinId = val.CoinId
		tmp.Icon = val.CoinInfo.Icon
		tmp.Platform = val.CoinInfo.Platform
		tmp.Chain = val.CoinInfo.Chain
		coinsResp = append(coinsResp, tmp)
	}

	return coinsResp, nil
}

func (c *SupportedChain) Add() error {
	chain := map[string]interface{}{
		"platform_id": c.PlatformId,
		"coin_id":     c.CoinId,
	}

	if err := models.AddSupportedChain(chain); err != nil {
		return err
	}

	return nil
}

func (c *SupportedChain) ExistById() (bool, error) {
	return models.ExistSupportedChainById(c.ID)
}

func (c *SupportedChain) Count() (int, error) {
	return models.GetSupportedChainTotal(c.getMaps())
}

func (c *SupportedChain) Delete() error {
	return models.DeleteSupportedChain(c.ID)
}

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

	if c.ID != 0 {
		maps["id"] = c.ID
	}

	if c.CoinId != 0 {
		maps["coin_id"] = c.CoinId
	}

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