import 'dart:async';

import 'package:flutter/widgets.dart';
import 'package:mnemo_cards_common/mnemo_cards_common.dart';
import 'package:rxdart/rxdart.dart';

import '../features/analytics/analytics.dart';


class UserStateHolder extends ChangeNotifier {
  UserDto? _dto;
  final _streamController = StreamController<UserDto?>.broadcast();

  static final _instance = UserStateHolder._();

  UserStateHolder._();

  factory UserStateHolder() => _instance;

  void setUser(UserDto dto) {
    _dto = dto.copyWith();
    Analytics.setUser(dto);

    notifyListeners();
    _streamController.add(_dto);
  }

  void clear() {
    _dto = null;
    notifyListeners();
    _streamController.add(null);
  }

  Stream<UserDto> get asStream => asNullableStream.whereNotNull();

  Stream<UserDto?> get asNullableStream =>
      _streamController.stream.startWith(_dto);

  UserDto? get user => _dto;
}
