import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math' as math;
import 'package:absenkuv3/Bloc/AuthBloc.dart';
import 'package:absenkuv3/Bloc/Lembur/AbsensiLemburBloc.dart';
import 'package:absenkuv3/Bloc/NavigatorBloc.dart';
import 'package:absenkuv3/Repository/Model/PageModel/mLemburPage.dart';
import 'package:absenkuv3/Repository/Model/mAbsensi.dart' as mAbsensi;
import 'package:absenkuv3/Repository/Model/mLembur.dart';
import 'package:absenkuv3/Repository/Model/mLogin.dart';
import 'package:absenkuv3/Setting/PengaturanBahasa.dart';
import 'package:absenkuv3/Setting/value_image.dart';
import 'package:absenkuv3/UI/Modul/Absensi/KomponenAbsensi.dart';
import 'package:absenkuv3/UI/Template/Camera/Bloc/CameraBloc.dart';
import 'package:absenkuv3/UI/Template/Camera/Model/CameraModel.dart';
import 'package:absenkuv3/UI/Template/Camera/UI/HalamanCamera.dart';
import 'package:absenkuv3/UI/Template/CameraIOS/cameraIOS.dart';
import 'package:absenkuv3/UI/Template/FaceRecognition/Bloc/FaceRecognitionBloc.dart'
as recognition;
import 'package:absenkuv3/UI/Template/FaceRecognition/Bloc/FaceRegistrationBloc.dart';
import 'package:absenkuv3/UI/Template/FaceRecognition/UI/FaceRecognition.dart';
import 'package:absenkuv3/UI/Template/FaceRecognition/UI/FaceRegistration.dart';
import 'package:absenkuv3/UI/Template/buttonAbsensi.dart';
import 'package:absenkuv3/UI/Template/style.dart';
import 'package:absenkuv3/UI/Template/templateButton.dart';
import 'package:absenkuv3/UI/Template/templateForm.dart';
import 'package:absenkuv3/UI/Template/templateIconInformation.dart';
import 'package:app_settings/app_settings.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../../Repository/Model/mFace.dart';
import '../../../Repository/sharedPreference.dart';
import '../../Template/CameraX/Bloc/FaceXBloc.dart';
import '../../Template/CameraX/Model/CameraXRespon.dart';

class HalamanPengajuanLembur extends StatefulWidget {
  @override
  _HalamanPengajuanLemburState createState() => _HalamanPengajuanLemburState();
}

class _HalamanPengajuanLemburState extends State<HalamanPengajuanLembur>
    with WidgetsBindingObserver {
  GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();
  CameraModel? cameraModel;
  TextEditingController keterangan = new TextEditingController();
  LemburHariIniRespon? dataRespon;
  DataHariIni? dataHariIni;
  mAbsensi.Lokasi? dataLokasi;
  StatusButtonAbsensi? statusButtonAbsensi;
  String? jenisPeringatan;
  bool lifeCycleStateInit = true;

  static const MethodChannel methodChannel = MethodChannel('absenku/camerax');
  static const EventChannel eventChannel = EventChannel('absenku/camerax/report');

  String _reportStatus = ' {"foto":"","matrix":""}';
  String? foto = "";
  String? matrix = "";
  var registrasi = false;
  Position? position;
  String? kamera2;

  @override
  void initState() {
    WidgetsBinding.instance.addObserver(this);
    BlocProvider.of<AbsensiLemburBloc>(context)
        .add(CekAbsenLemburEvent(context));
    BlocProvider.of<FaceXBloc>(context).add(InitialDialog(context));
    super.initState();
  }

  void didChangeAppLifecycleState(AppLifecycleState state) async {
    if (state == AppLifecycleState.resumed && lifeCycleStateInit) {
      BlocProvider.of<AbsensiLemburBloc>(context)
          .add(CekAbsenLemburEvent(context));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        key: scaffoldKey,
        body: BlocBuilder<AuthBloc, LoginRespon>(
            builder: (BuildContext context, LoginRespon loginRespon) {
              return BlocListener<AbsensiLemburBloc, AbsensiLemburState>(
                listener: (BuildContext context, AbsensiLemburState state) {
                  if (state is PeringatanState) {
                    jenisPeringatan = state.jenisPeringatan;
                    popUpPeringatanV2(state.message, context);
                  }
                },
                child: FutureBuilder<PageLemburModel>(
                    future: PengaturanBahasa().lembur(),
                    builder: (context, snapshot) {
                      if (snapshot.connectionState == ConnectionState.done) {
                        return BlocBuilder<AuthBloc, LoginRespon>(builder:
                            (BuildContext context, LoginRespon loginRespon) {
                          return BlocConsumer<AbsensiLemburBloc,
                              AbsensiLemburState>(
                            listener: (context, state) {
                              if (state is PeringatanState) {
                                jenisPeringatan = state.jenisPeringatan;
                                popUpPeringatan(state.message, context);
                              }
                            },
                            builder: (context, state) {
                              Set<Marker> _markers = {};
                              Completer<GoogleMapController> _controller =
                              Completer();
                              CameraPosition _initPosition =
                              CameraPosition(target: LatLng(-6.9932, 110.4203));
                              if (state is AbsensiLemburLoading) {
                                return Container(
                                  height: double.infinity,
                                  width: double.infinity,
                                  child: Center(
                                      child: CircularProgressIndicator(
                                        strokeWidth: 8,
                                      )),
                                );
                              } else if (state is AbsensiLemburFailure) {
                                return Container(
                                  height: double.infinity,
                                  width: double.infinity,
                                  decoration: CustomStyle.boxDecoration,
                                  child: Center(
                                    child: Text(state.errorMessage),
                                  ),
                                );
                              } else if (state is AbsensiLemburSuccess) {
                                animateCamera(_controller, state.position!);
                                _markers = state.markers;
                                dataRespon = state.dataAbsen;

                                dataHariIni = dataRespon!.dataHariIni;
                                dataLokasi = dataRespon!.dataLokasi;
                                statusButtonAbsensi =
                                    dataRespon!.statusButtonAbsensi;

                                return Stack(
                                  children: [
                                    Container(
                                      height: double.infinity - 30,
                                      width: double.infinity,
                                      child: GoogleMap(
                                        myLocationButtonEnabled: true,
                                        compassEnabled: true,
                                        zoomControlsEnabled: false,
                                        initialCameraPosition: _initPosition,
                                        mapType: MapType.normal,
                                        onMapCreated:
                                            (GoogleMapController controllers) {
                                          _controller.complete(controllers);
                                        },
                                        markers: _markers,
                                      ),
                                    ),
                                    Align(
                                      alignment: Alignment.topCenter,
                                      child: Padding(
                                        padding: const EdgeInsets.fromLTRB(
                                            20, 40, 20, 0),
                                        child: Row(
                                          mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                          children: [
                                            TombolIcon(
                                                icon: Icons.keyboard_arrow_left,
                                                onClick: () =>
                                                    BlocProvider.of<NavigatorBloc>(
                                                        context)
                                                        .add(NavigatePop(context))
                                              // BlocProvider.of<NavigatorBloc>(context)
                                              //     .add(NavigateRemoveToDashboard(context)),
                                            ),
                                            TombolIcon(
                                              icon: Icons.refresh,
                                              onClick: () => BlocProvider.of<
                                                  AbsensiLemburBloc>(context)
                                                  .add(
                                                  CekAbsenLemburEvent(context)),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                    Align(
                                      alignment: Alignment.bottomCenter,
                                      child: Padding(
                                        padding: const EdgeInsets.symmetric(
                                            horizontal: 12),
                                        child: Container(
                                          child: Column(
                                            mainAxisAlignment:
                                            MainAxisAlignment.end,
                                            children: [
                                              Container(
                                                width: double.infinity,
                                                decoration:
                                                CustomStyle.boxDecoration,
                                                child: Padding(
                                                  padding:
                                                  const EdgeInsets.symmetric(
                                                      horizontal: 0,
                                                      vertical: 8),
                                                  child: Column(
                                                    children: [
                                                      IconInformation(
                                                        icon: ValueImage.iconLokasi,
                                                        title: snapshot
                                                            .data!
                                                            .menuLembur!
                                                            .data!
                                                            .lokasi,
                                                        subtitle:
                                                        dataLokasi!.ketLokasi ??
                                                            '',
                                                        sizeIcon: 33,
                                                      ),
                                                      Divider(),
                                                      IconInformation(
                                                        icon: ValueImage.iconRadius,
                                                        title: snapshot
                                                            .data!
                                                            .menuLembur!
                                                            .data!
                                                            .akurasi,
                                                        subtitle:
                                                        '${state.position!.accuracy.round().toString()} Meter',
                                                        sizeIcon: 29,
                                                      ),
                                                    ],
                                                  ),
                                                ),
                                              ),
                                              SizedBox(
                                                height: 10,
                                              ),
                                              BlocBuilder<FaceXBloc, FaceXState>(
                                                  builder: (BuildContext __context,
                                                      FaceXState faceX) {
                                                    if (faceX is FaceXStateInit) {
                                                      return Container(
                                                        width: double.infinity,
                                                        decoration:
                                                        CustomStyle.boxDecoration,
                                                        child: Padding(
                                                          padding: const EdgeInsets.all(
                                                              12.0),
                                                          child: Row(
                                                            children: [
                                                              Expanded(
                                                                flex: 4,
                                                                child: Row(
                                                                  children: [
                                                                    Expanded(
                                                                      flex: 1,
                                                                      child: Container(
                                                                        width: 35,
                                                                        height: 35,
                                                                        child: Image.asset(
                                                                            ValueImage
                                                                                .iconLembur),
                                                                      ),
                                                                    ),
                                                                    SizedBox(
                                                                      width: 10,
                                                                    ),
                                                                    Expanded(
                                                                      flex: 5,
                                                                      child: Column(
                                                                        crossAxisAlignment:
                                                                        CrossAxisAlignment
                                                                            .start,
                                                                        children: [
                                                                          Text(
                                                                            snapshot
                                                                                .data!
                                                                                .menuLembur!
                                                                                .data!
                                                                                .lemburMulai!,
                                                                            overflow:
                                                                            TextOverflow
                                                                                .ellipsis,
                                                                            style: TextStyle(
                                                                                fontSize:
                                                                                CustomStyle.fontSizeSmall -
                                                                                    1,
                                                                                color: CustomStyle
                                                                                    .fontColorGrey),
                                                                          ),
                                                                          SizedBox(
                                                                            height: 2,
                                                                          ),
                                                                          Text(
                                                                            "${dataHariIni!.tglLemburMulai} - ${dataHariIni!.jamLemburMulai}",
                                                                            // overflow: TextOverflow.ellipsis,
                                                                            style: TextStyle(
                                                                                fontSize:
                                                                                CustomStyle.fontSizeSmall -
                                                                                    1,
                                                                                color: CustomStyle
                                                                                    .fontColorBlack,
                                                                                fontWeight:
                                                                                FontWeight.w600),
                                                                          ),
                                                                          Divider(
                                                                            thickness:
                                                                            1,
                                                                          ),
                                                                          Text(
                                                                            snapshot
                                                                                .data!
                                                                                .menuLembur!
                                                                                .data!
                                                                                .lemburSelesai!,
                                                                            overflow:
                                                                            TextOverflow
                                                                                .ellipsis,
                                                                            style: TextStyle(
                                                                                fontSize:
                                                                                CustomStyle.fontSizeSmall -
                                                                                    1,
                                                                                color: CustomStyle
                                                                                    .fontColorGrey),
                                                                          ),
                                                                          SizedBox(
                                                                            height: 2,
                                                                          ),
                                                                          Text(
                                                                            "${dataHariIni!.tglLemburSelesai} - ${dataHariIni!.jamLemburSelesai}",
                                                                            // overflow: TextOverflow.ellipsis,
                                                                            style: TextStyle(
                                                                                fontSize:
                                                                                CustomStyle.fontSizeSmall -
                                                                                    1,
                                                                                color: CustomStyle
                                                                                    .fontColorBlack,
                                                                                fontWeight:
                                                                                FontWeight.w600),
                                                                          ),
                                                                        ],
                                                                      ),
                                                                    )
                                                                  ],
                                                                ),
                                                              ),
                                                              SizedBox(
                                                                width: 12,
                                                              ),
                                                              Expanded(
                                                                flex: 3,
                                                                child: ButtonAbsensi(
                                                                  mulai: statusButtonAbsensi!
                                                                      .toggleAbsenLembur,
                                                                  mulaiTitle: snapshot
                                                                      .data!
                                                                      .menuLembur!
                                                                      .button!
                                                                      .btnMulai,
                                                                  selesaiTitle: snapshot
                                                                      .data!
                                                                      .menuLembur!
                                                                      .button!
                                                                      .btnSelesai,
                                                                  enable: true,
                                                                  onClick: () async {
                                                                    String? kamera = loginRespon.dataLogin!.kamera;
                                                                    // if (kamera == '2') {
                                                                    // if (Platform.isIOS) {
                                                                    //   kamera = '1';
                                                                    // }
                                                                    // }
                                                                    var status =
                                                                    await Permission
                                                                        .camera
                                                                        .status;
                                                                    if (status
                                                                        .isDenied ||
                                                                        status
                                                                            .isPermanentlyDenied) {
                                                                      if (status
                                                                          .isPermanentlyDenied) {
                                                                        jenisPeringatan =
                                                                        "PermissionGPS";
                                                                        popUpPeringatan(
                                                                            snapshot
                                                                                .data!
                                                                                .menuLembur!
                                                                                .messageKonfirmasi!
                                                                                .kamera!,
                                                                            context);
                                                                      } else {
                                                                        await Permission
                                                                            .camera
                                                                            .request();
                                                                      }
                                                                    } else {
                                                                      lifeCycleStateInit =
                                                                      false;
                                                                      if (kamera == '1')
                                                                        cameraModel = await Navigator.push<
                                                                            CameraModel>(
                                                                            context,
                                                                            MaterialPageRoute(
                                                                                builder: (_) => routeAbsensi(
                                                                                    loginRespon
                                                                                        .dataLogin!,
                                                                                    statusButtonAbsensi!.toggleAbsenLembur!
                                                                                        ? snapshot.data!.menuLembur!.button!.btnMulai!
                                                                                        : snapshot.data!.menuLembur!.button!.btnSelesai!,
                                                                                    snapshot.data!.menuLembur!.data!.registrasi!,
                                                                                    snapshot.data!.menuLembur!.data!.titlePeringatan!,
                                                                                    snapshot.data!.menuLembur!.button!.btnClose)));
                                                                      else if (kamera ==
                                                                          '2') {
                                                                        // cameraModel = routeAbsensi2(loginRespon.dataLogin!, statusButtonAbsensi!.toggleAbsenLembur!?'Mulai Lembur':'Selesai Lembur');
                                                                        cameraModel = await routeCameraX(
                                                                            loginRespon
                                                                                .dataLogin!,
                                                                            statusButtonAbsensi!.toggleAbsenLembur!
                                                                                ? snapshot
                                                                                .data!
                                                                                .menuLembur!
                                                                                .button!
                                                                                .btnMulai!
                                                                                : snapshot
                                                                                .data!
                                                                                .menuLembur!
                                                                                .button!
                                                                                .btnSelesai!,
                                                                            state
                                                                                .position,
                                                                            kamera!,
                                                                            faceX
                                                                                .faceRegistrationInfoRespon);
                                                                      } else {
                                                                        XFile?
                                                                        pickedFile =
                                                                        await ImagePicker().pickImage(
                                                                            source: ImageSource
                                                                                .camera,
                                                                            imageQuality:
                                                                            75,
                                                                            maxWidth:
                                                                            400);
                                                                        if (pickedFile !=
                                                                            null)
                                                                          cameraModel = CameraModel(
                                                                              base64Encode(
                                                                                  File(pickedFile.path)
                                                                                      .readAsBytesSync()),
                                                                              pickedFile
                                                                                  .path);
                                                                      }
                                                                      if (cameraModel !=
                                                                          null)
                                                                        openDialog(
                                                                            statusButtonAbsensi!
                                                                                .toggleAbsenLembur!
                                                                                ? 'lembur_mulai'
                                                                                : 'lembur_selesai',
                                                                            state
                                                                                .position,
                                                                            context,
                                                                            rotate: kamera ==
                                                                                '1'
                                                                                ? true
                                                                                : false);
                                                                    }
                                                                  },
                                                                ),
                                                              )
                                                            ],
                                                          ),
                                                        ),
                                                      );
                                                    } else {
                                                      return CircularProgressIndicator(
                                                        strokeWidth: 1,
                                                      );
                                                    }
                                                  }),
                                              SizedBox(
                                                height: 10,
                                              )
                                            ],
                                          ),
                                        ),
                                      ),
                                    )
                                  ],
                                );
                              } else {
                                return Container();
                              }
                            },
                          );
                        });
                      } else {
                        return CircularProgressIndicator(strokeWidth: 8);
                      }
                    }),
              );
            }));
  }

  popUpPeringatanV2(String? message, _context) {
    showDialog(
        barrierDismissible: false,
        context: _context,
        builder: (BuildContext context) {
          return WillPopScope(
            onWillPop: keluarV2,
            child: AlertDialog(
              shape: RoundedRectangleBorder(
                  borderRadius:
                  BorderRadius.all(Radius.circular(CustomStyle.boxRadius))),
              content: SingleChildScrollView(
                reverse: true,
                child: Column(
                  children: <Widget>[
                    Text(
                      message!,
                      style: TextStyle(color: Colors.redAccent),
                    ),
                  ],
                ),
              ),
            ),
          );
        });
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  Future<void> animateCamera(Completer<GoogleMapController> _controller,
      Position currentLocation) async {
    final GoogleMapController controller = await _controller.future;
    // print("lat :${currentLocation.latitude}");
    // print("long :${currentLocation.longitude}");
    CameraPosition _current = CameraPosition(
        target: LatLng(currentLocation.latitude, currentLocation.longitude),
        zoom: 17.151926040649414);
    controller.animateCamera(CameraUpdate.newCameraPosition(_current));
  }

  openDialog(String jenisAbsen, Position? position, BuildContext _context,
      {bool rotate = true}) {
    final double mirror = math.pi;
    keterangan.text = '';
    showDialog(
        context: _context,
        builder: (BuildContext context) {
          return AlertDialog(
            shape: RoundedRectangleBorder(
                borderRadius:
                BorderRadius.all(Radius.circular(CustomStyle.boxRadius))),
            content: SingleChildScrollView(
              reverse: true,
              child: Column(
                children: <Widget>[
                  Column(
                    children: [
                      rotate
                          ? Transform(
                          alignment: Alignment.center,
                          child: Platform.isAndroid
                              ? Image.file(File(cameraModel!.path))
                              : Image.memory(base64Decode(cameraModel!.base64)),
                          transform: Matrix4.rotationY(mirror))
                          : Platform.isAndroid
                          ? Image.file(File(cameraModel!.path))
                          : Image.memory(base64Decode(cameraModel!.base64)),
                      SizedBox(
                        height: 12,
                      ),
                      TemplateForm(
                        formHeight: CustomStyle.formHeight,
                        adaValidasi: true,
                        controller: keterangan,
                        color: Colors.grey[600],
                        titleText: "Keterangan",
                        radius: CustomStyle.formRadius,
                        hintText: "Keterangan",
                      ),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      TemplateButton(
                        onClick: () => BlocProvider.of<NavigatorBloc>(context)
                            .add(NavigatePop(context)),
                        label: "Batal",
                        color: Colors.transparent,
                        contentColor: CustomStyle.color1,
                        fontSize: CustomStyle.fontSizeNormal,
                        bold: true,
                      ),
                      TemplateButton(
                        onClick: () {
                          BlocProvider.of<NavigatorBloc>(_context)
                              .add(NavigatePop(_context));
                          BlocProvider.of<AbsensiLemburBloc>(_context)
                              .add(TambahAbsenLemburEvent(
                            _context,
                            scaffoldKey,
                            DataAbsensi(
                                jenisAbsen: jenisAbsen,
                                lokasiAbsen: dataLokasi!.namaLokasi,
                                latitude: position!.latitude.toString(),
                                longitude: position.longitude.toString(),
                                keteranganAbsen: keterangan.text,
                                foto: cameraModel!.base64),
                          ));
                        },
                        label: "Kirim",
                        color: Colors.transparent,
                        contentColor: CustomStyle.color1,
                        fontSize: CustomStyle.fontSizeNormal,
                        bold: true,
                      )
                    ],
                  )
                ],
              ),
            ),
          );
        });
  }

  popUpPeringatan(String message, _context) {
    showDialog(
        barrierDismissible: false,
        context: _context,
        builder: (BuildContext context) {
          return WillPopScope(
            onWillPop: keluar,
            child: AlertDialog(
              shape: RoundedRectangleBorder(
                  borderRadius:
                  BorderRadius.all(Radius.circular(CustomStyle.boxRadius))),
              content: SingleChildScrollView(
                reverse: true,
                child: Column(
                  children: <Widget>[
                    Text(
                      message,
                      style: TextStyle(color: Colors.redAccent),
                    ),
                    jenisPeringatan == 'PermissionGPS'
                        ? Column(
                      children: [
                        SizedBox(
                          height: 24,
                        ),
                        Align(
                          alignment: Alignment.centerRight,
                          child: GestureDetector(
                            onTap: () {
                              BlocProvider.of<NavigatorBloc>(context)
                                  .add(NavigatePop(_context));
                              AppSettings.openAppSettings();
                            },
                            child: Text(
                              "Request Permission",
                              style: TextStyle(
                                  color: CustomStyle.color1,
                                  fontWeight: FontWeight.w600,
                                  fontSize:
                                  CustomStyle.fontSizeSmall + 1),
                            ),
                          ),
                        )
                      ],
                    )
                        : Container(),
                  ],
                ),
              ),
            ),
          );
        });
  }

  Future<bool> keluarV2() async {
    BlocProvider.of<NavigatorBloc>(context)
        .add(NavigateRemoveToDashboard(context));
    return false;
  }

  Future<bool> keluar() async {
    /*if(jenisPeringatan=='PermissionGPS')
      BlocProvider.of<NavigatorBloc>(context)
          .add(NavigateRemoveToDashboard(context));
    else{
      BlocProvider.of<NavigatorBloc>(context)
          .add(NavigatePop(context));
      BlocProvider.of<NavigatorBloc>(context)
          .add(NavigatePop(context));
    }*/
    BlocProvider.of<NavigatorBloc>(context).add(NavigatePop(context));
    BlocProvider.of<NavigatorBloc>(context).add(NavigatePop(context));
    return false;
  }

  routeAbsensi(
      DataLogin dataLogin, String konteks, String registrasi, title, btnLabel) {
    print("LOCK FACE ${dataLogin.lockFaceRecognition}");
    if (dataLogin.lockFaceRecognition! &&
        (dataLogin.faceData == null || dataLogin.faceData == '')) {
      return BlocProvider(
          create: (BuildContext context) =>
              FaceRegistrationBloc(InitializeProgress()),
          child: FaceRegistration(registrasi, title, btnLabel));
    } else if (dataLogin.lockFaceRecognition! &&
        (dataLogin.faceData != null || dataLogin.faceData != '')) {
      return BlocProvider(
          create: (BuildContext context) =>
              recognition.FaceRecognitionBloc(recognition.InitializeProgress()),
          child: FaceRecognition(konteks));
    } else {
      return BlocProvider(
        create: (BuildContext context) =>
            CameraBloc(InitializeCameraProgress()),
        child: CameraApp(konteks, true),
      );
    }
  }

  routeCameraX(DataLogin dataLogin, String konteks, Position? position, String kamera, List<DataFaceRegistrationInfo>? peringatan) {
    if(Platform.isIOS){
      _startCameraXActivity(position, kamera, false);
    }else{
      if (dataLogin.lockFaceRecognition! && (dataLogin.faceData == null || dataLogin.faceData == '')) {
        _startCameraXFace(true, position, kamera, peringatan);
      } else if (dataLogin.lockFaceRecognition! && (dataLogin.faceData != null || dataLogin.faceData != '')) {
        _startCameraXFace(false, position, kamera, peringatan);
      } else {
        _startCameraXActivity(position, kamera, false);
      }
    }
  }

  Future<void> _startCameraXActivity(Position? position, String kamera, bool kameraBelakang) async {
    if(Platform.isIOS){
      Navigator.push(context, MaterialPageRoute(builder: (_)=> CameraIosPage(1)))
          .then((value) {
        if(value != null){
          String _base64Image = base64Encode(value);
          setState(() {
            this.position = position;
            this.kamera2 = "camera";
          });
          cameraModel = CameraModel(_base64Image, "");
          openDialog(
              statusButtonAbsensi!.toggleAbsenLembur!
                  ? 'lembur_mulai'
                  : 'lembur_selesai',
              this.position,
              context,
              rotate: false);
        }
      });
    }else{
      setState(() {
        this.position = position;
        this.kamera2 = "camera";
        // registrasi = register;
      });
      try {
        eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
        await methodChannel.invokeMethod('startCameraXActivity', {
          "kameraBelakang": kameraBelakang,
          "header_text": statusButtonAbsensi!.toggleAbsenLembur!
                ? 'Lembur Mulai'
                : 'Lembur Selesai'
        });
      } on PlatformException catch (e) {
        debugPrint("Failed to Invoke: '${e.message}'.");
      }
    }
  }

  Future<void> _startCameraXFace(bool register, Position? position,
      String kamera, List<DataFaceRegistrationInfo>? peringatan) async {
    LoginRespon data = await sharedPreferences().getUserData();
    double cosineThreshold = data.dataLogin!.cosineThreshold!;
    double l2Threshold = data.dataLogin!.l2Threshold!;
    String faceData = "";
    setState(() {
      this.position = position;
      this.kamera2 = "face";
      registrasi = register;
    });
    if (register) {
      faceData = "";
    } else {
      String faceDataString = data.dataLogin!.faceData!;
      String modifiedString =
      faceDataString.replaceAll('[', '').replaceAll(']', '');
      faceData = modifiedString;
    }
    String stringPeringatan = "";
    print("peringatan" + peringatan!.length.toString());
    for (int i = 0; i < peringatan.length; i++) {
      stringPeringatan = stringPeringatan + peringatan[i].isi.toString() + "| ";
    }
    print("strinngperingatan" + stringPeringatan);

    try {
      eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
      await methodChannel.invokeMethod('startFaceCameraXActivity', {
        'matrix': faceData,
        'register': register,
        'peringatan': stringPeringatan.toString(),
        'cosineThreshold': cosineThreshold,
        'l2Threshold': l2Threshold,
      });
    } on PlatformException catch (e) {
      debugPrint("Failed to Invoke: '${e.message}'.");
    }
  }

  void _onEvent(Object? event) {
    setState(() {
      _reportStatus = event.toString();
      CameraXRespon cameraXRespon = cameraXResponFromJson(_reportStatus);

      foto = cameraXRespon.foto;
      matrix = cameraXRespon.matrix;

      // String? compressFoto2;

      cameraModel =
          CameraModel(base64Encode(File(foto!).readAsBytesSync()), foto!);
      var fotoBase64 = base64Encode(File(foto!).readAsBytesSync());
      List<double> numbersList = [];
      try {
        numbersList = matrix
            .toString()
            .replaceAll('[', '') // Menghapus karakter "[" dari string
            .replaceAll(']', '') // Menghapus karakter "]" dari string
            .split(',') // Memisahkan angka-angka berdasarkan tanda koma ","
            .map((String number) => double.parse(
            number.trim())) // Mengubah setiap string menjadi double
            .toList(); // Mengonversi hasil ke dalam List<double>
      } catch (e) {
        numbersList = [];
        print("error $e");
      }
      print("ininumberlist ${numbersList}");

      if (registrasi) {
        BlocProvider.of<FaceXBloc>(context).add(
            registrasiEvent(context, scaffoldKey, numbersList, fotoBase64,false));
      } else {
        openDialog(
            statusButtonAbsensi!.toggleAbsenLembur!
                ? 'lembur_mulai'
                : 'lembur_selesai',
            this.position,
            context,
            rotate: this.kamera2 == 'face' ? true : false);
      }
    });
    print("Foto12: $foto");
    print("Matrix12: $matrix");
    print("INIREPORT ${_reportStatus.toString()}");
    debugPrint(_reportStatus);
  }

  void _onError(Object error) {
    setState(() {
      _reportStatus = 'Camera status: ${error.toString()}';

      print("INIREPORT : ${error.toString()}");
    });
  }
}
