package models

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

type CoinGas struct {
	Model

	CoinName string `json:"coin_name"`
	Low      string `json:"low"`
	Average  string `json:"average"`
	High     string `json:"high"`
}

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),
	}
	if err := db.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 = ?", coin_name).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 ExistCoinGasByName(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
}

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

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

	return false, nil
}
