package models

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

type CoinGas struct {
	CoinName string `json:"coin_name"`
	Low      string `json:"low"`
	Average  string `json:"average"`
	High     string `json:"high"`
	Switch   int8   `json:"switch"`
}

func (c CoinGas) TableName() string {
	return setting.DatabaseSetting.Name_Sources + ".wallet_coin_gas"
}

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

	return ct, nil
}

func AddCoinGas(data map[string]interface{}) (error) {
	CoinGas := CoinGas{
		CoinName: data["coin_name"].(string),
		Low:      data["low"].(string),
		Average:  data["average"].(string),
		High:     data["high"].(string),
		Switch:   data["switch"].(int8),
	}
	if err := db.Debug().Create(&CoinGas).Error; err != nil {
		return err
	}

	return nil
}

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

	return nil
}

func DeleteCoinGas(id int) error {
	if err := db.Where("id = ?", id).Delete(CoinGas{}).Error; err != nil {
		return err
	}

	return nil
}

func GetCoinGas(coin_name string) (*CoinGas, error) {
	var gas CoinGas
	err := db.Where("coin_name = ? and switch = ?", coin_name, 1).First(&gas).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

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

	return &gas, nil
}

func Exist(coin_name string) (bool, error) {
	var coinGas CoinGas
	err := db.Where("coin_name = ?", coin_name).First(&coinGas).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}

	if coinGas.CoinName != "" {
		return true, nil
	}

	return false, nil
}
