package models

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

type Wallet struct {
	Model

	Name        string  `gorm:"size:255;not null;" json:"name"`
	DownloadUrl string  `gorm:"not null;" json:"download_url"`
	Introduce   string  `gorm:"not null;" json:"introduce"`
	//ChainId     int     `gorm:"not null;default:0" json:"chain_id"`
	//IssueCharge float32 `gorm:"not null;default:0.00" json:"issue_charge"`
	//ChargeUnit  string  `gorm:"not null;default:BTY" json:"charge_unit"`
}

func (w Wallet) TableName() string {
	return setting.DatabaseSetting.Name_Sources + ".coin_platform"
}

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

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

	return false, nil
}

func GetWalletTotal(maps interface{}) (int, error) {
	var count int
	if err := db.Model(&Wallet{}).Where(maps).Count(&count).Error; err != nil {
		return 0, err
	}

	return count, nil
}

func GetWallets(pageNum, pageSize int, maps interface{}) ([]*Wallet, error) {
	var wallets []*Wallet
	err := db.Where(maps).Offset(pageNum).Limit(pageSize).Find(&wallets).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return wallets, nil
}

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

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

	return &wallet, nil
}

func AddWallet(data map[string]interface{}) (error) {
	wallet := Wallet{
		Name:        data["name"].(string),
		DownloadUrl: data["download_url"].(string),
		Introduce:   data["introduce"].(string),
		//ChargeUnit:  data["charge_unit"].(string),
		//IssueCharge: data["issue_charge"].(float32),
		//ChainId:     data["chain_id"].(int),
	}
	if err := db.Create(&wallet).Error; err != nil {
		return err
	}

	return nil
}

func EditWallet(id int, data interface{}) error {
	if err := db.Model(&Wallet{}).Where("id = ?", id).Updates(data).Error; err != nil {
		return err
	}

	return nil
}

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

	return nil
}
