package ws_handler

import (
	"sync"
)

var UserMgr *userManager

type userManager struct {
	userMap map[int32]*Client
	sync.RWMutex
}

func init() {
	UserMgr = &userManager{
		userMap: make(map[int32]*Client),
	}
}

func (m *userManager) Add(uid int32, client *Client) {
	m.Lock()
	defer m.Unlock()
	m.userMap[uid] = client
}

func (m *userManager) Delete(uid int32) {
	m.Lock()
	defer m.Unlock()
	delete(m.userMap, uid)
}

func (m *userManager) GetAll() map[int32]*Client {
	m.RLock()
	defer m.RUnlock()

	copyMap := make(map[int32]*Client, len(m.userMap))
	for k, v := range m.userMap {
		copyMap[k] = v
	}
	return copyMap
}

func (m *userManager) GetAllInterface() []interface{} {
	m.RLock()
	defer m.RUnlock()

	r := make([]interface{}, 0)
	for _, v := range m.userMap {
		r = append(r, v)
	}
	return r
}

func (m *userManager) GetByUID(uid int32) *Client {
	m.RLock()
	defer m.RUnlock()
	return m.userMap[uid]
}
