import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

import 'package:pshared/provider/permissions.dart';

import 'package:pweb/app/router/pages.dart';
import 'package:pweb/widgets/error/snackbar.dart';

import 'package:pweb/generated/i18n/app_localizations.dart';


class PermissionsLoader extends StatelessWidget {
  final Widget child;

  const PermissionsLoader({super.key, required this.child});

  @override
  Widget build(BuildContext context) => Consumer<PermissionsProvider>(builder: (context, provider, _) {
    if (provider.isLoading) return const Center(child: CircularProgressIndicator());
    if (provider.error != null) {
      postNotifyUserOfErrorX(
        context: context, 
        errorSituation: AppLocalizations.of(context)!.errorLogin, 
        exception: provider.error!,
      );
      navigateAndReplace(context, Pages.login);
    }
    if ((provider.error == null) && (provider.permissions.isEmpty)) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        provider.load();
      });
      return const Center(child: CircularProgressIndicator());
    }
    return child;
  });
}
