import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:generp/services/api_calling.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';
import '../Utils/commonServices.dart';
import 'HomeScreenNotifier.dart';

class Scanloginprovider extends ChangeNotifier {
  PermissionStatus _cameraPermissionStatus = PermissionStatus.denied;
  QRViewController? _qrViewController;
  bool _hasPermission = false;
  final GlobalKey scannerKey = GlobalKey(debugLabel: 'QR');
  bool get hasPermission => _hasPermission;
  Future<void> checkPermission1() async {
    // Check camera permissions
    var status = await Permission.camera.status;
    try {
      if (status.isGranted) {
        _hasPermission = true;
      } else if (status.isDenied || status.isRestricted) {
        // Request camera permissions if denied or restricted
        await Permission.camera.request();
        status = await Permission.camera.request();
        if (status.isGranted) {
          _hasPermission = true;
        } else {
          _hasPermission = false;
        }
      }
    } catch (e) {}
  }

  Future<void> requestCameraPermission() async {
    PermissionStatus status = await Permission.camera.request();

    _cameraPermissionStatus = status;
    // print(_cameraPermissionStatus);

    try {
      if (_cameraPermissionStatus.isGranted) {
        _hasPermission = true;
      } else if (_cameraPermissionStatus.isDenied ||
          _cameraPermissionStatus.isRestricted ||
          _cameraPermissionStatus.isPermanentlyDenied) {
        _hasPermission = false;
        await Permission.camera.request();
      }
    } catch (e) {}
  }

  void onQRViewCreated(QRViewController controller, context) {
    // print("QRVIEW");
    var HomeProvider = Provider.of<HomescreenNotifier>(context, listen: false);
    _qrViewController = controller;
    controller.scannedDataStream.listen((scanData) {
      controller.pauseCamera();
      Map<String, dynamic> obj = jsonDecode(scanData.code!);
      if (obj["type"] == "login") {
        if (kDebugMode) {
          print("type:" + obj["type"]);
          print("token:" + (obj["data"]["token"]));
        }

        controller.pauseCamera();

        LoadQRAPIFunction(context, obj["type"], (obj["data"]["token"]));
      }
    });
  }

  Future<void> LoadQRAPIFunction(context, type, token) async {
    try {
      var homeProvider = Provider.of<HomescreenNotifier>(
        context,
        listen: false,
      );
      final data = await ApiCalling.QRLoginRequestAPI(
        homeProvider.empId,
        homeProvider.session,
        type,
        token,
      );

      if (data != null) {
        if (data.sessionExists == 1) {
          if (data.error == 0) {
            Navigator.pop(context);
            toast(context, "Login Successful!!");
          } else if (data.error == 1) {
            toast(context, data.message);
            toast(context, "Session Expired, Please Try Again!!");
          } else if (data.error == 2) {
            toast(context, data.message);
            toast(context, "Something Went wrong, Please Try Again!!");
          } else {
            toast(context, "Something Went wrong, Please Try Again!");
          }
        } else {
          toast(context, "Your session has expired, please login again!");
        }
      } else {}
    } on Error catch (e) {
      print(e.toString());
    }
  }
}
