#!/bin/sh
# Smoke test for the installed listen library; runs offline.
set -eu

work=$(mktemp -d)
export HOME="$work"
trap 'rm -rf "$work"' EXIT INT TERM

DART=$(command -v dart 2>/dev/null || true)
[ -n "$DART" ] || DART=/usr/lib/dart/bin/dart

mkdir -p "$work/.dart_tool"
cat > "$work/.dart_tool/package_config.json" <<'JSON'
{"configVersion":2,"packages":[{"name":"listen","rootUri":"file:///usr/share/dart/packages/listen","packageUri":"lib/","languageVersion":"3.10"},{"name":"meta","rootUri":"file:///usr/share/dart/packages/meta","packageUri":"lib/","languageVersion":"3.5"}]}
JSON

cat > "$work/main.dart" <<'DART'
import "package:listen/listen.dart";

void main() {
  final notifier = ValueNotifier<int>(0);
  var calls = 0;
  notifier.addListener(() => calls++);

  notifier.value = 1;
  notifier.value = 2;
  if (calls != 2) {
    throw StateError("expected 2 listener calls, got $calls");
  }
  if (notifier.value != 2) {
    throw StateError("unexpected value: ${notifier.value}");
  }

  // Setting the same value must not notify.
  notifier.value = 2;
  if (calls != 2) {
    throw StateError("notified on an unchanged value ($calls calls)");
  }

  final counter = ChangeNotifier();
  var notified = false;
  counter.addListener(() => notified = true);
  counter.notifyListeners();
  if (!notified) {
    throw StateError("ChangeNotifier did not notify its listener");
  }

  counter.dispose();
  notifier.dispose();
  print("listen smoke test passed");
}
DART

cd "$work"
"$DART" run main.dart
