import { CliLeaf } from '@alwaysai/alwayscli';
import { yesCliInput } from '../../cli-inputs';
import { checkUserIsLoggedInComponent } from '../../components/user';
import { CliAuthenticationClient, CliRpcClient } from '../../infrastructure';

export async function getDeviceList() {
  const { username } = await CliAuthenticationClient().getInfo();
  const deviceList = await CliRpcClient().getUserDevices({
    user_name: username
  });
  return deviceList;
}

export const deviceList = CliLeaf({
  name: 'list',
  description: 'List all available devices',
  namedInputs: {
    yes: yesCliInput
  },
  async action(_, { yes }) {
    await checkUserIsLoggedInComponent({ yes });
    const deviceList = await getDeviceList();
    const deviceTable = deviceList.reduce((acc, device) => {
      const { uuid, friendly_name, description, host_name } = device;
      acc[uuid] = { name: friendly_name, description, address: host_name };
      return acc;
    }, {});
    console.table(deviceTable);
  }
});
