package models

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

type RecommendCoin struct {
	Model

	Id         int    `json:"primary_key,omitempty"`
	Cid        int    `json:"cid"`
	Recommend  int    `json:"recommend"`
	PlatformId int    `json:"platform_id"`
	Sort       int    `json:"sort"`
	Type       int    `json:"type"`

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

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").Where(maps).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),
		Recommend:  data["recommend"].(int),
		PlatformId: data["platform_id"].(int),
		Sort:       data["sort"].(int),
		Type:       data["type"].(int),
	}
	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
}
