package models

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

type CoinTicker struct {
	Model

	CoinName   string `json:"coin_name"`
	CoinId     int    `json:"coin_id"` //币种ID`
	Ticker     string `json:"ticker"`
	PlatformId int    `json:"platform_id"`

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

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

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

func GetCoinTicker(id int) (*CoinTicker, error) {
	var ticker CoinTicker
	err := db.Where("id = ?", id).First(&ticker).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	err = db.Model(&ticker).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return &ticker, nil
}

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

	return ct, nil
}

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

	if coinTicker.PlatformId > 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"].(string),
		PlatformId: data["platform_id"].(int),
	}
	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(id int) error {
	if err := db.Where("id = ?", id).Delete(CoinTicker{}).Error; err != nil {
		return err
	}

	return nil
}

func ExistById(id int) (bool, error) {
	var coinTicker CoinTicker
	err := db.Select("id").Where("id = ?", id).First(&coinTicker).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}

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

	return false, nil
}
