import 'package:flutter/foundation.dart';

import 'package:pshared/models/auth/state.dart';
import 'package:pshared/provider/account.dart';

import 'package:pweb/models/account/account_loader.dart';


class AccountLoaderController extends ChangeNotifier {
  AccountProvider? _provider;
  AuthState? _handledState;
  AccountLoaderAction? _action;
  Object? _error;

  AccountLoaderAction? get action => _action;
  Object? get error => _error;

  void update(AccountProvider provider) {
    if (identical(_provider, provider)) return;
    _provider?.removeListener(_handleProviderChanged);
    _provider = provider;
    _provider?.addListener(_handleProviderChanged);
    _evaluate(provider);
  }

  AccountLoaderAction? consumeAction() {
    final action = _action;
    _action = null;
    return action;
  }

  void _handleProviderChanged() {
    final provider = _provider;
    if (provider == null) return;
    _evaluate(provider);
  }

  void _evaluate(AccountProvider provider) {
    if (_handledState == provider.authState) return;
    _handledState = provider.authState;

    switch (provider.authState) {
      case AuthState.error:
        _error = provider.error ?? Exception('Authorization failed');
        _action = AccountLoaderAction.showErrorAndGoToLogin;
        notifyListeners();
        break;
      case AuthState.empty:
        _error = null;
        _action = AccountLoaderAction.goToLogin;
        notifyListeners();
        break;
      default:
        break;
    }
  }

  @override
  void dispose() {
    _provider?.removeListener(_handleProviderChanged);
    super.dispose();
  }
}
