

import 'package:app_hit_a_wod/src/models/stripe_user.model.dart';
import 'package:app_hit_a_wod/src/models/subscription_selection.model.dart';
import 'package:app_hit_a_wod/src/providers/api.provider.dart';
import 'package:app_hit_a_wod/src/providers/auth.provider.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:rxdart/rxdart.dart';

class CancelSubscriptionBloc {
  
  BuildContext _context;
  ApiProvider _api;
  SubscriptionSelection _ss;
  StripeUser _stripeUser;

  BehaviorSubject<String> _statusSubject = new BehaviorSubject(); //'init', 'loading', 'done'
  Stream<String> get statusStream => _statusSubject.stream;

  CancelSubscriptionBloc(this._context, this._api, this._ss, this._stripeUser) {
    _statusSubject.sink.add('init');
  }

  cancel() async {
    _statusSubject.sink.add('loading');
    try {
      var resp = await _api.cancelUserSubscription(_ss.us.id);

      //ja s'ha cancelat
      final auth = Provider.of<AuthProvider>(_context, listen: false);
      auth.refreshToken();
      Navigator.pop(_context);

    } on DioError catch(e) {
      _statusSubject.sink.add('init');
      _statusSubject.sink.addError(e.response!=null ? e.response.data["error"] : e.toString());
      return false;
    } on Exception catch(e) {
      _statusSubject.sink.add('init');
      _statusSubject.sink.addError(e.toString());
      return false;
    }
  }

} 