package models

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

type PlatformChain struct {
	Model

	Id         int `json:"primary_key,omitempty"`
	PlatformId int `json:"platform_id"`
	ChainId    int `json:"chain_id"`
	IsPrimary  int `json:"is_primary"`

	ChainInfo *UserChain `gorm:"foreignkey:ChainId" json:"chain"`
}

func (c PlatformChain) TableName() string {
	return setting.DatabaseSetting.Name_Sources + ".wallet_platform_chain"
}

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

	return &PlatformChain, nil
}

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

	return count, nil
}

func GetPlatformChains(maps interface{}) ([]*PlatformChain, error) {
	var platformChain []*PlatformChain
	err := db.Preload("ChainInfo").Where(maps).Find(&platformChain).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return platformChain, nil
}

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

	return nil
}
