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"`
}

type ReqTicketInfo struct {
	Addr string `json:"addr" binding:"required"`
	Page int32 `json:"page"`
	Pagesize int32 `json:"pagesize"`
	Detail bool `json:"detail"`
	Order string `json:"order"`
}

// 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) (int64, error) {
	var count int64
	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(req *ReqTicketInfo) ([]*RaspMinerTxs, error) {
	var txs []*RaspMinerTxs
	if req.Order == "" {
		req.Order = "desc"
	}
	maps := map[string]interface{}{"miner":req.Addr}
	err := db.Where(maps).Order("time "+req.Order).Offset((req.Page-1)*req.Pagesize).Limit(req.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
}

