package ws_handler

import (
	"sync"
)

var UserMgr *userManager

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

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

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

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

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

	copyMap := make(map[int64]*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) GetByUSN(usn int64) *Client {
	m.RLock()
	defer m.RUnlock()
	return m.userMap[usn]
}
