package models

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

type RecommendCoin struct {
	Model

	Id              int     `json:"primary_key,omitempty"`
	Cid             int     `json:"cid"`
	Sort            int     `json:"sort"`
	PlatformId      int     `json:"platform_id"`
	Type            uint8   `json:"type"`
	CategoryId      uint8   `json:"category_id"`

	CoinInfo   *Coin                    `gorm:"foreignkey:Cid" json:"coin"`
	WalletType *WalletRecommendCategory `gorm:"foreignkey:CategoryId" json:"type"`
}

func (c RecommendCoin) TableName() string {
	return setting.DatabaseSetting.Name_Sources + ".wallet_recommend_coin"
}

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

	return &recommendCoin, nil
}

func ExistRecommendCoinById(id int) (bool, error) {
	var coinRecommend RecommendCoin
	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 GetRecommendCoinTotal(maps interface{}) (int, error) {
	var count int
	if err := db.Model(&RecommendCoin{}).Where(maps).Count(&count).Error; err != nil {
		return 0, err
	}

	return count, nil
}

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

	return coinsRecommend, nil
}

func AddRecommendCoin(data map[string]interface{}) (error) {
	coinRecommend := RecommendCoin{
		Cid:        data["cid"].(int),
		Sort:       data["sort"].(int),
		PlatformId: data["platform_id"].(int),
		CategoryId: data["category_id"].(uint8),
		Type:       data["type"].(uint8),
	}
	if err := db.Create(&coinRecommend).Error; err != nil {
		return err
	}

	return nil
}

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

	return nil
}

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

	return nil
}

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

	return nil
}
