package state

import (
	"context"
	"sync"
	"sync/atomic"
)

type BLock struct {
	obLock    *ObjectLock
	chl       chan struct{}
	version   int32
	lock      *sync.Mutex
}

func NewBLock(ctx context.Context) *BLock {
	return &BLock{
		obLock: NewObjectLock(ctx),
		chl: make(chan struct{},0),
		lock: new(sync.Mutex),
	}
}


func (bLock *BLock) Lock0(version int32) {
	bLock.lock.Lock()
	println("block lock version:",bLock.version,"version:",version)
	if atomic.LoadInt32(&bLock.version) == version {
		bLock.chl <- struct{}{}
		atomic.AddInt32(&bLock.version,1)
		bLock.obLock.Lock0()
	}

	select {
	case <-bLock.chl:
		bLock.obLock.UnLock0()
	}
}

func (bLock *BLock) UnLock0() {
	bLock.lock.Unlock()
}

func (bLock *BLock) Lock()  {
	bLock.obLock.Lock()
}

func (bLock *BLock) UnLock() {
	bLock.obLock.Unlock()
}