package models

import "github.com/jinzhu/gorm"

func UpdateBlock(rt *RaspMinerTxs,rs *RaspMinerStat) error {
	tx := db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		return err
	}
	var prev RaspMinerStat
	var res RaspMinerTxs
	err := tx.Model(&RaspMinerStat{}).Where(&RaspMinerStat{Addr:rs.Addr}).First(&prev).Error
	if err != nil {
		//不存在创建
		if err == gorm.ErrRecordNotFound {
			if err := tx.Create(&rs).Error;err != nil {
				tx.Rollback()
				return err
			}
		} else {
			tx.Rollback()
			return err
		}
	} else {
		//存在 则更新状态
		if err := tx.Model(&RaspMinerStat{}).Where("Addr = ? ",rs.Addr).Update(&RaspMinerStat{
			MinedAmount:prev.MinedAmount+rs.MinedAmount,
			MinedTicketCount:prev.MinedTicketCount+rs.MinedTicketCount,
			MiningTicketCount:prev.MiningTicketCount+rs.MiningTicketCount,
			Height:rs.Height,
			Time:rs.Time,
		}).Error;err != nil {
			tx.Rollback()
			return err
		}
	}

	if err := tx.Where(&RaspMinerTxs{Height:rt.Height}).Assign(&rt).FirstOrCreate(&res).Error;err != nil {
		tx.Rollback()
		return err
	}

	if err := tx.Model(&RaspConfig{}).Where("config = ? ","height").Update("Height",rt.Height).Error;err != nil {
		tx.Rollback()
		return err
	}

	return tx.Commit().Error
}

func UpdateBlocks(rt map[int64]*RaspMinerTxs,rs map[string]*RaspMinerStat,height int64) error {
	tx := db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		return err
	}
	for _,v := range rt {
		var res RaspMinerTxs
		if err := tx.Where(&RaspMinerTxs{Height:v.Height}).Assign(v).FirstOrCreate(&res).Error;err != nil {
			tx.Rollback()
			return err
		}
	}
	for _,v:= range rs {
		var prev RaspMinerStat

		err := tx.Model(&RaspMinerStat{}).Where(&RaspMinerStat{Addr:v.Addr}).First(&prev).Error
		if err != nil {
			//不存在创建
			if err == gorm.ErrRecordNotFound {
				if err := tx.Create(v).Error;err != nil {
					tx.Rollback()
					return err
				}
			} else {
				tx.Rollback()
				return err
			}
		} else {
			//存在 则更新状态
			if err := tx.Model(&RaspMinerStat{}).Where("Addr = ? ",v.Addr).Update(&RaspMinerStat{
				MinedAmount:prev.MinedAmount+v.MinedAmount,
				MinedTicketCount:prev.MinedTicketCount+v.MinedTicketCount,
				MiningTicketCount:prev.MiningTicketCount+v.MiningTicketCount,
				Height:v.Height,
				Time:v.Time,
			}).Error;err != nil {
				tx.Rollback()
				return err
			}
		}

	}


	if err := tx.Model(&RaspConfig{}).Where("config = ? ","height").Update("Height",height).Error;err != nil {
		tx.Rollback()
		return err
	}

	return tx.Commit().Error
}
