package models

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

type Fee struct {
	Model

	Id              int     `json:"primary_key,omitempty"`
	Cid             int     `json:"cid"`
	PlatformId      int     `json:"platform_id"`
	FeesType        uint8   `json:"fees_type"`
	Fees            float32 `json:"fees"`
	TransactionFees float32 `json:"transaction_fees"`
	CoinName        string  `json:"coin_name"`

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

func (c Fee) TableName() string {
	return setting.DatabaseSetting.Name_Sources + ".wallet_fees"
}

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

	return &fee, nil
}

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

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

	return false, nil
}

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

	return count, nil
}

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

	return fee, nil
}

func AddFee(data map[string]interface{}) (error) {
	fee := Fee{
		Cid:        data["cid"].(int),
		PlatformId: data["platform_id"].(int),
		CoinName:   data["coin_name"].(string),
	}
	if err := db.Create(&fee).Error; err != nil {
		return err
	}

	return nil
}

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

	return nil
}

func Search(maps interface{}) (*Fee, error) {
	var fee Fee
	err := db.Where(maps).Find(&fee).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return &fee, nil
}

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

	return nil
}
