import { Dimensions, Platform, StyleSheet,Vibration } from 'react-native';
import React from 'react';
import { useCameraDevices, useFrameProcessor, Camera } from 'react-native-vision-camera';
import { useNavigation } from '@react-navigation/native';
import { Svg, Rect } from 'react-native-svg';
import {
  BarcodeFormat,
  scanBarcodes,
} from 'vision-camera-code-scanner';
import { runOnJS } from 'react-native-reanimated';

export const CodigoQrnew = () => {
  const [hasPermission, setHasPermission] = React.useState(false);
  const devices = useCameraDevices();
  const device = devices.back;
  const navigate = useNavigation<any>();
  const [frameWidth] = React.useState(1280);
  const [frameHeight] = React.useState(720);
  const scanRegion = {
    left: 5,
    top: 20,
    width: 90,
    height: 50
  }

  const frameProcessor = useFrameProcessor(frame => {
    'worklet';
    let dataJson:Object|string|null = null
    const detectedBarcodes = scanBarcodes(frame, [BarcodeFormat.QR_CODE], {
      checkInverted: true,
    });
    if (detectedBarcodes.length > 0) {
      const data:any = detectedBarcodes[0]!.content.data
      try{
        dataJson = JSON.parse(data)
      }
      catch (e){
        dataJson = data
      }
      
      runOnJS(Vibration.vibrate)(100);
      if (typeof dataJson === 'object' && dataJson!.hasOwnProperty('valor')) {
        runOnJS(navigate.navigate)('DatosBancarios', { data: data });
      }
      console.log("no contiene los datos")
      
    }
  }, []);
  React.useEffect(() => {
    (async () => {
      const status = await Camera.requestCameraPermission();
      setHasPermission(status === 'authorized');
    })();
  }, []);
  const getViewBox = () => {
    const frameSize = getFrameSize();
    const viewBox = "0 0 " + frameSize.width + " " + frameSize.height;
    return viewBox;
  }

  const getFrameSize = (): { width: number, height: number } => {
    let width: number, height: number;
    if (HasRotation()) {
      width = frameHeight;
      height = frameWidth;
    } else {
      width = frameWidth;
      height = frameHeight;
    }
    return { width: width, height: height };
  }

  const HasRotation = () => {
    let value = false
    if (Platform.OS === 'android') {
      if (!(frameWidth > frameHeight && Dimensions.get('window').width > Dimensions.get('window').height)) {
        value = true;
      }
    }
    return value;
  }

  return (
    device != null &&
    hasPermission && (
      <>
        <Camera
          style={StyleSheet.absoluteFill}
          device={device}
          isActive={true}
          frameProcessor={frameProcessor}
          frameProcessorFps={5}
        />

        <Svg preserveAspectRatio='xMidYMid slice' style={StyleSheet.absoluteFill} viewBox={getViewBox()}>

          <Rect
            x={scanRegion.left / 100 * getFrameSize().width}
            y={scanRegion.top / 100 * getFrameSize().height}
            width={scanRegion.width / 100 * getFrameSize().width}
            height={scanRegion.height / 100 * getFrameSize().height}
            fill="none"
            strokeWidth="2"
            stroke="green"
          />
        </Svg>
      </>

    )
  );
};

