

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:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:rxdart/rxdart.dart';

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

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

  RenewSubscriptionManuallyBloc(BuildContext this._context, ApiProvider this._api, StripeUser this._stripeUser, SubscriptionSelection this._ss) {
    _statusSubject.sink.add("init");
  }

  renew() async {
    _statusSubject.sink.add('loading');
    try {
      //1. Generar comanda
      int box_id = _ss.box.id;
      var resp = await _api.renewUserSubscription(_ss.us.id, {
        "renew": 0,
        "pricing_id": _ss.pricing.id,
        "start_date": DateFormat('yyyy-MM-dd').format(_ss.us.end_date),
        "payment_type_id": 1, //slug: 'stripe'
        "override": 0,
        "box_id": box_id
      });

      //2. Pagar
      var resp2 = await _api.payUserSubscription(_ss.us.id, {
        "box_id": box_id,
        "payment_type_slug": "stripe"
      });

      final auth = Provider.of<AuthProvider>(_context, listen: false);
      auth.refreshToken();
      Navigator.pop(_context);

      return true;
      
    } 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;
    }
  }
  
}