import '../../about/external/initial/LoginData.dart';
import '../../about/internal/application/MeDescription.dart';
import '../../about/internal/application/UserDetails.dart';
import '../parent/ParentViewModel.dart';
import 'ConnectLogin.dart';

class ViewLogin extends ParentViewModel {
  ConnectLogin connection;

  ViewLogin(super.context, this.connection);

  void login(LoginData request) async {
    if (!await hasNetwork(() => login(request))) return;

    showLoading("Signing in");

    try {
      final response = await getDataManager().login(request);

      final Map<String, dynamic> body = response.data;

      await getDataManager().setMyDescription(MeDescription(
        id: body['id'] ?? "",
        name: body['name'] ?? "",
        token: body['token'] ?? "",
      ));

      final UserDetails details = UserDetails.fromJson(body);

      await getDataManager().setUserDetails(details);

      closeLoading();

      connection.onLoggedIn(details);
    } catch (e) {
      handleError(e, () => login(request), () => dismissError(), "Retry");
    }
  }
}
