

import 'package:app_hit_a_wod/src/blocs/validators.dart';
import 'package:app_hit_a_wod/src/providers/api.provider.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:rxdart/rxdart.dart';

class ChangePasswordBloc with Validators {

  BuildContext _context;
  ApiProvider _api;

  BehaviorSubject<String> _statusSubject = new BehaviorSubject(); //init, loading, done
  Stream<String> get statusStream => _statusSubject.stream;
  BehaviorSubject<String> _tokenSubject = new BehaviorSubject();
  Stream<String> get tokenStream => _tokenSubject.stream.transform(validarNotEmpty);
  get setToken => _tokenSubject.sink.add;
  BehaviorSubject<String> _passwordSubject = new BehaviorSubject();
  Stream<String> get passwordStream => _passwordSubject.stream.transform(validarPassword);
  get setPassword => _passwordSubject.sink.add;

  static ChangePasswordBloc _instancia;
  factory ChangePasswordBloc(BuildContext context, ApiProvider api) {
    if(_instancia==null) _instancia = ChangePasswordBloc._internal(context, api);
    else _instancia._context = context;

    return _instancia;
  }
  ChangePasswordBloc._internal(BuildContext this._context, ApiProvider this._api) {
    _statusSubject.sink.add('init');
  } 

  resetPassword() async {
    _statusSubject.sink.add('init');
    try {
      var resp = await _api.changePassword(_tokenSubject.value, _passwordSubject.value);
      _statusSubject.sink.add('init');
      Navigator.pushReplacementNamed(_context, 'login');
      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;
    }
  }

}