package models

import (
	"bwallet/pkg/setting"
	"github.com/jinzhu/gorm"
)

type CoinTicker struct {
	CoinId     int     `json:"coin_id"`
	CoinName   string  `json:"coin_name"`
	Ticker     float32 `json:"ticker"`
	PlatformId uint8   `json:"platform_id"`

	//CoinInfo *Coin `gorm:"foreignkey:coin_id" json:"coin_info"`
}

type CoinTickerResp struct {
	CoinId int     `json:"coin_id"`
	Ticker float32 `json:"ticker"`
	Name   string  `json:"name"`
}

func (c CoinTicker) TableName() string {
	return setting.DatabaseSetting.Name_Sources + ".wallet_coin_ticker"
}

func GetCoinsTicker(maps interface{}) ([]*CoinTicker, error) {
	var ct []*CoinTicker
	err := db.Where(maps).Find(&ct).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return ct, nil
}

func ExistCoin(coin_id int, platform_id uint8) (bool, error) {
	var coinTicker CoinTicker
	err := db.Where("coin_id = ? and platform_id = ?", coin_id, platform_id).First(&coinTicker).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}

	if coinTicker.CoinId > 0 {
		return true, nil
	}

	return false, nil
}

func AddCoinTicker(data map[string]interface{}) (error) {
	coinTicker := CoinTicker{
		CoinName:   data["coin_name"].(string),
		CoinId:     data["coin_id"].(int),
		Ticker:     data["ticker"].(float32),
		PlatformId: data["platform_id"].(uint8),
	}
	if err := db.Create(&coinTicker).Error; err != nil {
		return err
	}

	return nil
}

func EditCoinTicker(maps interface{}, data interface{}) error {
	if err := db.Model(&CoinTicker{}).Where(maps).Updates(data).Error; err != nil {
		return err
	}

	return nil
}

func DeleteCoinTicker(coin_id int, platform_id uint8) error {
	if err := db.Where("coin_id = ? and platform_id = ?", coin_id, platform_id).Delete(CoinTicker{}).Error; err != nil {
		return err
	}

	return nil
}
