import '../src/rust/api.dart' as rust;

class OwnClientSnapshotState {
  const OwnClientSnapshotState({
    required this.channelId,
    required this.inputMuted,
    required this.outputMuted,
    required this.talkPowerOk,
    required this.talkPower,
    required this.talkPowerGranted,
    this.neededTalkPower,
  });

  final BigInt channelId;
  final bool inputMuted;
  final bool outputMuted;
  final bool talkPowerOk;
  final int talkPower;
  final bool talkPowerGranted;
  final int? neededTalkPower;
}

OwnClientSnapshotState? ownClientSnapshotState(rust.BridgeSnapshot snapshot) {
  for (final client in snapshot.clients) {
    if (client.id != snapshot.ownClientId) continue;
    final neededTalkPower = _channelById(
      snapshot,
      client.channel,
    )?.neededTalkPower;
    return OwnClientSnapshotState(
      channelId: client.channel,
      inputMuted: client.inputMuted,
      outputMuted: client.outputMuted,
      talkPowerOk: _talkPowerOk(client, neededTalkPower),
      talkPower: client.talkPower,
      talkPowerGranted: client.talkPowerGranted,
      neededTalkPower: neededTalkPower,
    );
  }
  return null;
}

String snapshotChannelName(rust.BridgeSnapshot? snapshot, BigInt? channelId) {
  if (snapshot == null || channelId == null) return '';
  return _channelById(snapshot, channelId)?.name ?? '';
}

int? snapshotNeededTalkPower(rust.BridgeSnapshot? snapshot, BigInt? channelId) {
  if (snapshot == null || channelId == null) return null;
  return _channelById(snapshot, channelId)?.neededTalkPower;
}

rust.BridgeChannel? _channelById(
  rust.BridgeSnapshot snapshot,
  BigInt channelId,
) {
  return snapshot.channels
      .where((channel) => channel.id == channelId)
      .firstOrNull;
}

bool _talkPowerOk(rust.BridgeClient client, int? neededTalkPower) {
  if (client.talkPowerGranted) return true;
  return neededTalkPower == null || client.talkPower >= neededTalkPower;
}
