import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:grpc/grpc.dart';
export 'logger.dart';
import 'package:common_pub/common_pub.dart';
import 'styles/color_schemes.g.dart';
import 'view/login/login_view.dart';


Future<void> tryApi(Future<void> Function() call, {
  String? errTitle,
  Future<bool> Function(GrpcError err)? onError,
  Future<void> Function()? onSuccess,
  VoidCallback? onFinally,
}) async{

  Future<bool> handleError(GrpcError err) async {
    if(onError!= null){
      return onError(err);
    }
    if(err.code == StatusCode.unauthenticated){
      if (await LoginView.to()){
        try{
          await call();
        }catch(e){
          Get.snackbar('出错了', '未知错误');
        }
      }
      return true;
    }

    return false;
  }



  await tryCatchGrpc(
    call,
    onError: handleError,
    onSuccess: onSuccess,
    onFinally: onFinally,
  );
}


class Preview extends StatelessWidget{
  const Preview({super.key, required this.child});

  final Widget child;

  @override
  Widget build(BuildContext context) {
    return child;
  }
}


void runPreview(Widget child){
  runApp(GetMaterialApp(
      theme: ThemeData(useMaterial3: true, colorScheme: lightColorScheme),
      home: Preview(child: child)));
}
