package models

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

type TrusteeshipCoin struct {
	Model

	Id         int   `json:"primary_key,omitempty"`
	Cid        int   `json:"cid"`
	Sort       int   `json:"sort"`
	PlatformId int   `json:"platform_id"`

	CoinInfo   *Coin                    `gorm:"foreignkey:Cid" json:"coin"`
}

func (c TrusteeshipCoin) TableName() string {
	return setting.DatabaseSetting.Name_Sources + ".wallet_trusteeship_coin"
}

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

	return &trusteeshipCoin, nil
}

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

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

	return false, nil
}

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

	return count, nil
}

func GetTrusteeshipCoins(pageNum, pageSize int, maps interface{}) ([]*TrusteeshipCoin, error) {
	var coinsRecommend []*TrusteeshipCoin
	err := db.Preload("CoinInfo").Where(maps).Order("sort").Offset(pageNum).Limit(pageSize).Find(&coinsRecommend).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return coinsRecommend, nil
}

func AddTrusteeshipCoin(data map[string]interface{}) (error) {
	coinRecommend := TrusteeshipCoin{
		Cid:        data["cid"].(int),
		Sort:       data["sort"].(int),
		PlatformId: data["platform_id"].(int),
	}
	if err := db.Create(&coinRecommend).Error; err != nil {
		return err
	}

	return nil
}

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

	return nil
}

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

	return nil
}

func DeleteTrusteeshipByCondition(maps interface{}) error {
	if err := db.Where(maps).Delete(TrusteeshipCoin{}).Error; err != nil {
		return err
	}

	return nil
}
