import 'package:flutter/foundation.dart';
import 'package:shorebird_code_push/shorebird_code_push.dart';

class ShorebirdService {
  ShorebirdService._();

  static final ShorebirdService instance = ShorebirdService._();
  final ShorebirdUpdater _updater = ShorebirdUpdater();
  Patch? currentPatch;

  bool get isAvailable => _updater.isAvailable;

  Future<Patch?> readCurrentPatch() => _updater.readCurrentPatch();

  Future<void> initCurrentPatch() async {
    try {
      currentPatch = await _updater.readCurrentPatch();
    } catch (error) {
      debugPrint('Error reading current patch: $error');
    }
  }

  Future<UpdateStatus> checkForUpdate({
    UpdateTrack track = UpdateTrack.stable,
  }) {
    return _updater.checkForUpdate(track: track);
  }

  Future<void> downloadUpdate({UpdateTrack track = UpdateTrack.stable}) {
    return _updater.update(track: track).then((_) async {
      await initCurrentPatch();
    });
  }

  Future<void> checkForUpdateInBackground({
    UpdateTrack track = UpdateTrack.stable,
  }) async {
    if (!isAvailable) return;
    try {
      await _updater.checkForUpdate(track: track);
    } catch (error) {
      debugPrint('Shorebird background check failed: $error');
    }
  }
}
