package gio

import (
	"sync"
)

type MutexID struct {
	value map[any]struct{}
	mu    sync.Mutex
}

func (mux *MutexID) TryLock(id any) bool {
	if mux.value == nil {
		mux.value = make(map[any]struct{})
	}
	mux.mu.Lock()
	defer mux.mu.Unlock()
	if _, ok := mux.value[id]; ok {
		return false
	}
	mux.value[id] = struct{}{}
	return true
}

func (mux *MutexID) Unlock(id any) {
	mux.mu.Lock()
	if _, ok := mux.value[id]; ok {
		delete(mux.value, id)
	} else {
		panic("id not exist")
	}
	mux.mu.Unlock()
}

func (mux *MutexID) Close() error {
	mux.mu.Lock()
	clear(mux.value)
	mux.mu.Unlock()
	return nil
}
