package models

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

type RaspMinerStat struct {
	//Model
	Addr   string `json:"addr";gorm:"PRIMARY_KEY"`
	MinedAmount int64 `json:"mined_amount"`
	MinedTicketCount int64 `json:"mined_ticket_count"`
	MiningTicketCount int64 `json:"mining_ticket_count"`
	Total int64 `json:"total"`
	Balance int64 `json:"balance"`
	Frozen int64 `json:"frozen"`
	MinerStartTime int64 `json:"miner_start_time"`
	MinerEndTime int64 `json:"miner_end_time"`
	Height int64 `json:"height"`
	Time int64 `json:"time"`
}

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

	if stat.Addr != "" {
		return true, nil
	}

	return false, nil
}

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

	return count, nil
}


// GetAddr Get a single addr based on ID
func GetAddr(addr string) (*RaspMinerStat, error) {
	var stat RaspMinerStat
	err := db.Where("addr = ? ", addr).First(&stat).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return &stat, nil
}

func GetTicketSum() (int64,error) {
	var count int64
	if err := db.Model(&RaspMinerStat{}).Select("sum(mining_ticket_count) as count").Scan(&count).Error; err != nil {
		return 0,err
	}
	return count,nil

}

// EditAddr modify a single addr
func EditAddr(addr string, data interface{}) error {
	if err := db.Model(&RaspMinerStat{}).Where("addr = ? ", addr).Updates(data).Error; err != nil {
		return err
	}

	return nil
}

// AddAddr add a single addr
func AddAddr(data map[string]interface{}) error {
	stat := RaspMinerStat{
		Addr:         data["addr"].(string),
		MinedAmount:	data["mined_amount"].(int64),
		MinedTicketCount:         data["mined_ticket_count"].(int64),
		MiningTicketCount:          data["mining_ticket_count"].(int64),
		Total:       data["total"].(int64),
		Balance:     data["balance"].(int64),
		Frozen:         data["frozen"].(int64),
		Height:			data["height"].(int64),
		Time: data["time"].(int64),
	}
	if err := db.Create(&stat).Error; err != nil {
		return err
	}

	return nil
}



