package models

import (
	"github.com/jinzhu/gorm"
)

type RaspMinerTxs struct {
	//Model
	Miner   string `json:"miner";gorm:"INDEX"`
	ReturnAddr string `json:"return_addr"`
	Amount int64 `json:"amount"`
	Height int64 `json:"height"`
	Hash string `json:"hash"`
	Time int64 `json:"time"`
}

// ExistByAddr checks if an addr exists based on addr
func ExistByAddrHeight(addr string,height int64) (bool, error) {
	var txs RaspMinerTxs
	err := db.Select("miner").Where("miner = ? and height = ?", addr,height).First(&txs).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}

	if txs.Miner != "" {
		return true, nil
	}

	return false, nil
}

// GetAddrTotal gets the total number of addr based on the constraints
func GetMinerTxsTotal(addr string) (int, error) {
	var count int
	if err := db.Model(&RaspMinerTxs{}).Where("miner = ? ",addr).Count(&count).Error; err != nil {
		return 0, err
	}

	return count, nil
}

// GetAddrs gets a list of articles based on paging constraints
func GetMinerTxs(pageNum int32, pageSize int32, maps interface{}) ([]*RaspMinerTxs, error) {
	var txs []*RaspMinerTxs
	err := db.Where(maps).Offset(pageNum).Limit(pageSize).Find(&txs).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return txs, nil
}

// AddAddr add a single addr
func AddMinerTxs(data map[string]interface{}) error {
	tx := RaspMinerTxs{
		Miner:         data["addr"].(string),
		ReturnAddr: data["return_addr"].(string),
		Amount:	data["amount"].(int64),
		Height:			data["height"].(int64),
		Hash:data["hash"].(string),
		Time: data["time"].(int64),
	}
	if err := db.Create(&tx).Error; err != nil {
		return err
	}

	return nil
}

