import 'dart:async'; import 'package:seshat/data/services/api_client.dart'; import 'package:seshat/data/services/websocket_client.dart'; import 'package:seshat/domain/models/owner.dart'; import 'package:seshat/utils/result.dart'; class OwnerRepository { OwnerRepository({ required ApiClient apiClient, required WebsocketClient wsClient, }) : _apiClient = apiClient, _wsClient = wsClient; final ApiClient _apiClient; final WebsocketClient _wsClient; late final StreamSubscription sub; List? _cachedOwners; Owner? _sectionOwner; Future> get sectionOwner async { if (_sectionOwner != null) { return Result.ok(_sectionOwner!); } final result = await _apiClient.getSectionOwner(); switch (result) { case Ok(): _sectionOwner = result.value; break; default: break; } return result; } Future> getOwnerById(int id) async { if (_cachedOwners != null) { final result1 = _cachedOwners! .where((owner) => owner.id == id) .firstOrNull; if (result1 != null) { return Result.ok(result1); } } return await _apiClient.getOwnerById(id); } /// Adds an [Owner] to the database, and gets the resulting [Owner]. Future> addOwner( String firstName, String lastName, String contact, ) async { var response = await _apiClient.addOwner(firstName, lastName, contact); switch (response) { case Ok(): return Result.ok(response.value); case Error(): return Result.error(response.error); } } /// Fetches all the [Owner]s from the database, and subscribes to updates Future>> getOwners() async { if (_cachedOwners == null) { final result = await _apiClient.getOwners(); _wsClient.connect(); if (result is Ok>) { _cachedOwners = result.value; } sub = _wsClient.owners.listen((owner) { _cachedOwners!.add(owner); }); return result; } else { return Result.ok(_cachedOwners!); } } dispose() { sub.cancel(); } }