import 'dart:io';

import 'package:f_cache/manager.dart';
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';
import 'pb.dart' as pb;
import 'package:http/http.dart' as http;


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;
  }
}

typedef NetImage = pb.NetImage;

extension NetImageExt on NetImage{
  String? get md5Hex {
    if(md5.isEmpty){
      return null;
    }else{
      return md5.toHexString();
    }
  }

  Future<Reader> readerBuilder()async{
    final url = Uri.parse(this.url);
    var request = http.Request('GET', url);
    var response = await request.send();
    if (response.statusCode != 200) {
      throw HttpException('state: ${response.statusCode}', uri: url);
    }
    final length = response.contentLength ?? 0;
    return Reader(response.stream, length);
  }
  Future<void> preload()async{
    await CacheManager().getCached(id: md5Hex ?? '', readerBuilder: readerBuilder);
  }

}

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