import 'dart:async';
import '../../common/const_enum.dart';
import '../../utils/local_storage.dart';

class AuthenticationRepository {
  final _controller = StreamController<AuthenticationStatus>();

  Stream<AuthenticationStatus> get status async* {
    var status = await checkAuthStatus();
    switch (status) {
      case AuthenticationStatus.authenticated:
        yield AuthenticationStatus.authenticated;
        break;
      case AuthenticationStatus.unauthenticated:
        yield AuthenticationStatus.unauthenticated;
        break;
      default:
        yield AuthenticationStatus.unauthenticated;
        break;
    }
    yield* _controller.stream;
  }

  Future<AuthenticationStatus> checkAuthStatus() async {
    try {
      var isLogged = LocalStorage.getBool(LocalStorageKey.is_logged);
      if (isLogged) {
        return AuthenticationStatus.authenticated;
      } else {
        return AuthenticationStatus.unauthenticated;
      }
    } catch (_) {
      return AuthenticationStatus.unauthenticated;
    }
  }

  void logOut() {
    LocalStorage.clearUserInfo();
    _controller.add(AuthenticationStatus.unauthenticated);
  }

  void dispose() => _controller.close();
}
