// Device Registry - Tracks connected devices and their types
var sdl_input = use('sdl3/input')

var _devices = {}

// Register a device from a canonical event
function register(canon) {
  if (!canon || !canon.device_id) return
  var kind = null

  if (!_devices[canon.device_id]) {
    kind = 'keyboard'
    if (starts_with(canon.device_id, 'gp:')) kind = 'gamepad'
    else if (starts_with(canon.device_id, 'touch:')) kind = 'touch'

    _devices[canon.device_id] = {
      id: canon.device_id,
      kind: kind,
      gamepad_type: null,
      last_active: canon.time
    }
    
    // Get gamepad type for gamepads
    if (kind == 'gamepad' && canon.which != null) {
      _devices[canon.device_id].gamepad_type = sdl_input.gamepad_id_to_type(canon.which)
    }
  } else {
    _devices[canon.device_id].last_active = canon.time
  }
}

// Unregister a device (on disconnect)
function unregister(device_id) {
  delete _devices[device_id]
}

// Get device info
function get(device_id) {
  return _devices[device_id]
}

// Get device kind
function kind(device_id) {
  var dev = _devices[device_id]
  return dev ? dev.kind : 'keyboard'
}

// Get gamepad type for a device
function gamepad_type(device_id) {
  var dev = _devices[device_id]
  return dev ? dev.gamepad_type : null
}

// List all registered devices
function list() {
  return array(_devices)
}

// List devices of a specific kind
function list_by_kind(kind) {
  return filter(array(_devices), function(id) {
    return _devices[id].kind == kind
  })
}

return {
  register: register,
  unregister: unregister,
  get: get,
  kind: kind,
  gamepad_type: gamepad_type,
  list: list,
  list_by_kind: list_by_kind
}
