package cron

import (
	"ffie-admin/server/global"
	"time"

	"ffie-admin/server/model/brc"
	brcReq "ffie-admin/server/model/brc/request"

	"github.com/blockcypher/gobcy/v2"
	"go.uber.org/zap"
)

type BrcLockJob struct {
	JobName string
	Gobcy   gobcy.API
}

var isJobRunning = false

func (b BrcLockJob) Run() {
	b.JobName = "BRCJOB"
	if isJobRunning {
		return
	}
	isJobRunning = true
	defer func() {
		isJobRunning = false
	}()
	var err error
	b.Gobcy = global.GVA_GOBCY

	err = b.QueryLock()
	if err != nil {
		global.GVA_LOG.Error("QueryLock err: ", zap.Error(err))
	}
	global.GVA_LOG.Info("BrcLockJob Run success")
}

func (b BrcLockJob) QueryLock() error {
	var err error
	var lockList []brc.BrcLock
	err = global.GVA_DB.Model(&brc.BrcLock{}).Where("status = ?", brcReq.LockStatusHash).Find(&lockList).Error
	if err != nil {
		return err
	}
	for _, lock := range lockList {
		time.Sleep(time.Second * 5)
		tx, err := b.Gobcy.GetTX(lock.Hash, nil)
		if err != nil {
			global.GVA_LOG.Error("GetTX err: ", zap.Error(err))
			continue
		}
		if tx.BlockHeight == -1 {
			global.GVA_LOG.Error("GetTX blockheight -1 unconfirmed: ", zap.Any("height", -1))
			continue
		}
		if tx.Confirmations >= 6 {
			st := brcReq.LockStatusHashSucc
			block, err := b.Gobcy.GetBlock(tx.BlockHeight, "", nil)
			if err != nil {
				global.GVA_LOG.Error("GetBlock err: ", zap.Error(err))
				continue
			}
			stime := block.Time
			lock.Status = &st
			lock.StartTime = &stime
			err = global.GVA_DB.Save(&lock).Error
			if err != nil {
				return err
			}
		}

	}

	return nil
}
