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,openlist []*RaspOpen,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 openlist {
		var open RaspOpen
		if err := tx.Where(&RaspOpen{Hash:v.Hash}).Assign(v).FirstOrCreate(&open).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 {
			//存在 则更新状态
			new := make(map[string]interface{},0)
			new["mined_amount"] = prev.MinedAmount+v.MinedAmount
			new["mined_ticket_count"] = prev.MinedTicketCount+v.MinedTicketCount
			new["mining_ticket_count"] = prev.MiningTicketCount+v.MiningTicketCount
			new["height"] = v.Height
			new["time"] = v.Time

			if err := tx.Model(&RaspMinerStat{}).Where("Addr = ? ",v.Addr).Update(new).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
}
