// import 'dart:async';
// import 'dart:convert';
// import 'dart:io';
// import 'dart:math';

// import 'package:absenkuv3/Bloc/CustomFunction.dart';
// import 'package:absenkuv3/Bloc/NavigatorBloc.dart';
// import 'package:absenkuv3/Repository/Model/mLogin.dart';
// import 'package:absenkuv3/Repository/sharedPreference.dart';
// import 'package:absenkuv3/UI/Template/FaceRecognition/services/facenet.service.dart';
// import 'package:absenkuv3/UI/Template/FaceRecognition/services/ml_vision_service.dart';
// import 'package:camera/camera.dart';
// import 'package:flutter/material.dart';
// import 'package:flutter_bloc/flutter_bloc.dart';
// import 'package:absenkuv3/UI/Template/Camera/Model/CameraModel.dart';
// import 'package:flutter_image_compress/flutter_image_compress.dart';
// import 'package:google_ml_kit/google_ml_kit.dart';
// import 'package:image/image.dart' as resizeImage;
// import 'package:path_provider/path_provider.dart' as path_provider;
// import '../../style.dart';

// abstract class FaceRecognitionEvent{
//   BuildContext? context;
// }

// class Initialize extends FaceRecognitionEvent{
//   Initialize(BuildContext? _context){
//     context = _context;
//   }
// }

// class Dispose extends FaceRecognitionEvent{
//   Dispose(BuildContext _context){
//     context = _context;
//   }
// }

// class FrameFaces extends FaceRecognitionEvent{}

// class TakePicture extends FaceRecognitionEvent{
//   TakePicture(BuildContext _context){
//     context = _context;
//   }
// }

// abstract class FaceRecognitionState{
//   CameraController? controller;
//   Face? faceDetected;
//   Size? imageSize;
// }

// class InitializeProgress extends FaceRecognitionState{}

// class InitializeSuccess extends FaceRecognitionState{
//   InitializeSuccess(CameraController? _controller, Face? _faceDetected, Size? _imageSize){
//     controller = _controller;
//     faceDetected = _faceDetected;
//     imageSize = _imageSize;
//   }
// }

// class TakePictureSuccess extends FaceRecognitionState{
//   XFile? file;
//   TakePictureSuccess(this.file);
// }

// class FaceRecognitionBloc extends Bloc<FaceRecognitionEvent, FaceRecognitionState>{
//   late List<CameraDescription> cameras;
//   CameraController? controller;
//   XFile? file;
//   int? cameraId;
//   Size? imageSize;
//   MLVisionService _mlVisionService = MLVisionService();
//   final FaceNetService _faceNetService = FaceNetService();
//   Face? faceDetected;
//   bool _detectingFaces = false;
//   late InputImageRotation _inputImageRotation;
//   late CameraImage image;

//   FaceRecognitionBloc(FaceRecognitionState initialState) : super(initialState);

//   InputImageRotation rotationIntToImageRotation(int rotation) {
//     switch (rotation) {
//       case 90:
//         return InputImageRotation.Rotation_90deg;
//       case 180:
//         return InputImageRotation.Rotation_180deg;
//       case 270:
//         return InputImageRotation.Rotation_270deg;
//       default:
//         return InputImageRotation.Rotation_0deg;
//     }
//   }

//   @override
//   Stream<FaceRecognitionState> mapEventToState(FaceRecognitionEvent event) async*{
//     // TODO: implement mapEventToState
//     if(event is Initialize){
//       _mlVisionService.initialize();
//       await _faceNetService.loadModel();
//       yield InitializeProgress();
//       cameras = await availableCameras();
//       CameraDescription cameraDescription = cameras.firstWhere(
//             (CameraDescription camera) => camera.lensDirection == CameraLensDirection.front,
//       );
//       controller = new CameraController(cameraDescription, ResolutionPreset.high, enableAudio: false, imageFormatGroup: ImageFormatGroup.bgra8888,);


//       await controller!.initialize();

//       // sets the rotation of the image
//       this._inputImageRotation = rotationIntToImageRotation(
//         cameraDescription.sensorOrientation,
//       );

//       imageSize = Size(
//         controller!.value.previewSize!.height,
//         controller!.value.previewSize!.width,
//       );
//       startStream(event.context);
//       yield InitializeSuccess(controller, faceDetected, imageSize);
//     }
//     else if(event is FrameFaces){
//       yield InitializeSuccess(controller, faceDetected, imageSize);
//     }
//     else if(event is TakePicture){
//       await controller!.stopImageStream();
//       yield InitializeProgress();
//       if (!controller!.value.isInitialized) {
//         print('Error: select a camera first.');
//       }
//       if (!controller!.value.isTakingPicture) {
//         try {
//           if (faceDetected!=null) {
//             await controller!.setFocusMode(FocusMode.locked);
//             await Future.delayed(Duration(milliseconds: 500));
//             file = await controller!.takePicture();
//             final dir = await path_provider.getTemporaryDirectory();
//             File fileCompressed = File(file!.path);
//             resizeImage.Image? imageNew = resizeImage.decodeImage(fileCompressed.readAsBytesSync());
//             resizeImage.Image? thumbnail = resizeImage.copyResize(imageNew!, height: 400);
//             fileCompressed = new File(file!.path)
//               ..writeAsBytesSync(resizeImage.encodePng(thumbnail));
//             fileCompressed = await testCompressAndGetFile(File(file!.path), "${dir.absolute.path}/${DateTime.now()}.jpg");
//             _faceNetService.setCurrentPrediction(image, faceDetected!);
//             LoginRespon loginRespon = await sharedPreferences().getUserData();
//             List? faceDataMaster = loginRespon.dataLogin!.faceData!=null?json.decode(loginRespon.dataLogin!.faceData!):null;
//             if(faceDataMaster!=null){
//               if(_faceNetService.predict(faceDataMaster)!) {

//                 Navigator.pop(event.context!, CameraModel(
//                     base64Encode(fileCompressed.readAsBytesSync()),
//                     fileCompressed.path));
//                 yield TakePictureSuccess(file);
//                 Future.delayed(Duration(milliseconds: 500)).then((value) async{
//                   await controller!.dispose();
//                 });

//               }
//               else{
//                 faceDetected = null;
//                 CustomPopUp.show("Data wajah tidak sesuai saat registrasi wajah", event.context, isDismissible: false, doublePop: false, icon: Row(
//                   mainAxisAlignment: MainAxisAlignment.center,
//                   children: [
//                     Icon(Icons.cancel_outlined, color: Colors.redAccent, size: 46,),
//                     SizedBox(width: 6,),
//                     Text("Gagal", style: TextStyle(
//                       color: Colors.redAccent,
//                       fontWeight: FontWeight.w700,
//                       fontSize: CustomStyle.fontSizeHeader,
//                     ))
//                   ],), color: CustomStyle.fontColorBlack);
//                 BlocProvider.of<FaceRecognitionBloc>(event.context!).add(Initialize(event.context));
//               }
//             }
//             else{
//               CustomPopUp.show("Data wajah tidak ditemukan, silahkan registrasi wajah terlebih dahulu", event.context, isDismissible: false, doublePop: true);
//             }
//           }
//           else{
//             faceDetected = null;
//             CustomPopUp.show("Wajah tidak terdeteksi", event.context, isDismissible: false, doublePop: false, icon: Icon(Icons.close, color: Colors.redAccent, size: 46,), color: Colors.redAccent);
//             // startStream(event.context);
//             BlocProvider.of<FaceRecognitionBloc>(event.context!).add(Initialize(event.context));
//           }
//         } on CameraException catch (e) {
//           startStream(event.context);
//           print('ERROR $e');
//         }
//       }
//       else print('ERROR');
//     }
//     else if(event is Dispose){
//       print('DISPOSE');
//       await controller!.dispose();
//       BlocProvider.of<NavigatorBloc>(event.context!).add(NavigatePop(event.context));
//     }

//   }

//   startStream(BuildContext? context){
//     controller!.startImageStream((_image) async {
//       if (controller != null) {
//         // if its currently busy, avoids overprocessing
//         if (_detectingFaces) return;
//         _detectingFaces = true;
//         try {
//           List<Face> faces = await _mlVisionService.getFacesFromImage(_image, _inputImageRotation);
//           print("FACES ${faces.length}");
//           if (faces != null) {
//             if (faces.length > 0) {
//               // preprocessing the image
//               faceDetected = faces[0];
//               image = _image;
//             } else {
//               faceDetected = null;
//             }
//           }
//           _detectingFaces = false;
//         } catch (e) {
//           print(e);
//           _detectingFaces = false;
//         }
//         BlocProvider.of<FaceRecognitionBloc>(context!).add(FrameFaces());
//       }
//     });
//   }

//   Future<File> testCompressAndGetFile(File file, String targetPath) async {
//     var result = await FlutterImageCompress.compressAndGetFile(
//       file.absolute.path, targetPath,
//       quality: 75,
//     );

//     print(file.lengthSync());
//     print(result!.lengthSync());

//     return result;
//   }
// }