import React, { useEffect, useState, useMemo } from "react";
import { StyleSheet, View, Text } from "react-native";
import { forwardRef } from "react";
import Colors from "react-native-digitcamera/src/common/Colors";
import {
  WAITING_PERIOD,
  expectedPoseData,
  NO_OF_POSES,
} from "./StencilAnimation";
import {
  play,
  digitSoundList,
} from "react-native-digitcamera/src/common/DSound";

// var result = "Pose Result";
// var expectedPose = null;
var expectedPoseIndex = 0;
var waitId = null;
// var pauseResume = "pause";
const guide = {
  left: "Please move your device slightly right",
  right: "Please move your device slightly left",
  bottom: "Please move your device slightly Up",
  top: "Please move your device slightly Down",
  perfect: "Perfect Catch",
};
export const expectedPoseDataResult = {
  CHP: "Embossed Chassis",
  ECR: "Engine Chassis",
  WS: "Windshield",
  FS: "Front Side",
  FLC: "Front Left Corner",
  LS: "Left Side",
  BLC: "Back Left Corner",
  BS: "Back Side",
  BRC: "Back Right Corner",
  RS: "Right Side",
  FRC: "Front Right Corner",
  DBD: "Dashboard",
};
const ProcessRawOutput = forwardRef((props, multiRef) => {
  const { moveNextRef, rawOutputRef, pauseResumeRef, letsContinueAnimRef } =
    multiRef.current;
  const [expectedPose, setExpectedPose] = useState(null);
  const poseWaitingTimer = (pauseResumeRef) => {
    const constExpectedPose = expectedPose;
    const wId = setTimeout(() => {
      // clearTimeout(wId);
      moveToCheckNextPose(true, constExpectedPose, pauseResumeRef);
    }, WAITING_PERIOD);
    // setWaitId(waitId)
    waitId = wId;
  };

  if (expectedPose == null) {
    setExpectedPose(expectedPoseData[0]);
    poseWaitingTimer(pauseResumeRef);
  }

  const letsContinue = () => {
    poseWaitingTimer(pauseResumeRef);
  };
  letsContinueAnimRef.current = letsContinue;

  const [result, setResult] = useState("Pose Result");
  const [myPosition, setMyPosition] = useState("");

  const expectedPoseRender = useMemo(
    () => (
      <Text style={styles.poseText}>
        {expectedPoseDataResult[expectedPose]}
      </Text>
    ),
    [expectedPose]
  );
  const resultRender = useMemo(
    () => <Text style={styles.poseText}>{result}</Text>,
    [result]
  );
  const calculation = useMemo(
    () => play(digitSoundList[myPosition]),
    [myPosition]
  );

  const processOutput = (output, pauseResumeRef) => {
    console.log(
      "*** ProcessRawOutput puaseResume: " +
        pauseResumeRef.current() +
        "  output: " +
        JSON.stringify(output)
    );
    try {
      if (output && pauseResumeRef.current() == "resume") {
        const positions = output["positions"];
        const positionConfidence = output["positionConfidence"];
        const poses = output["poses"];
        const poseConfidence = output["poseConfidence"];

        const requiredPoseIndex = poses.indexOf(expectedPose);
        const requiredPoseConfidence = poseConfidence[requiredPoseIndex];

        const maxPosiConfi = Math.max.apply(null, positionConfidence);
        const indexMaxPosiConfi = positionConfidence.indexOf(maxPosiConfi);
        const myPosition = positions[indexMaxPosiConfi];
        console.log(
          "************************ ProcessRawOutput requiredPoseIndex: " +
            requiredPoseIndex +
            " requiredPoseConfidence: " +
            requiredPoseConfidence
        );
        // const maxPoseConfi = Math.max.apply(null, poseConfidence);
        // const indexMaxPoseConfi = poseConfidence.indexOf(maxPoseConfi);
        // var myPose = poses[indexMaxPoseConfi];
        var myPose = "";
        if (requiredPoseConfidence > 0.8) {
          myPose = "Perfect Catch";
          if (waitId) clearTimeout(waitId);
          moveToCheckNextPose(false, expectedPose, pauseResumeRef);
          setResult(`${myPose}`);
          setMyPosition(myPosition);
          setResult(`${guide[myPosition]}`);
        } else if (maxPosiConfi > 0.8) {
          // myPose = myPose + " but expected: " + expectedPose;
          // setResult(`${guide[myPosition]+" --> "+myPose}`);
          setMyPosition(myPosition);
          setResult(`${guide[myPosition]}`);
        }
        // console.log("*** ProcessRawOutput "+guide[myPosition]+"-"+myPose)
        // setResult(`${guide[myPosition]+"-"+myPose}`)
      }
    } catch (error) {
      console.log(error);
    }
  };

  rawOutputRef.current = processOutput;

  const moveToCheckNextPose = (isTimeout, processedPose, pauseResumeRef) => {
    if (pauseResumeRef.current() == "resume") {
      var newExpectedPoseIndex = expectedPoseIndex + 1;
      var newExpectedPose = expectedPoseData[newExpectedPoseIndex];
      if (newExpectedPose == undefined) {
        newExpectedPoseIndex = NO_OF_POSES - 1;
        newExpectedPose = expectedPoseData[newExpectedPoseIndex];
      }
      setExpectedPose(newExpectedPose);
      expectedPoseIndex = newExpectedPoseIndex;

      if (moveNextRef) {
        moveNextRef.current(newExpectedPoseIndex); // i.e. moveToCheckNextPose call will execute in AnimationEaseLinear
      }
      console.log(
        "****************************** ProcessRawOutput moveToNextPose isTimeout: " +
          isTimeout +
          " on pose: " +
          newExpectedPose
      );
      if (newExpectedPoseIndex != 0) {
        // In reset pose, we won't go for again to move next pose
        poseWaitingTimer(pauseResumeRef);
      }
    }
  };

  return (
    <View style={styles.guideStyle}>
      {expectedPoseRender}
      {resultRender}
    </View>
  );
});

const styles = StyleSheet.create({
  guideStyle: {
    width: "60%",
    position: "absolute",
    justifyContent: "center",
    alignSelf: "center",
    top: "50%",
    backgroundColor: "black",
  },
  poseText: {
    fontFamily: "Muli-Black",
    alignSelf: "center",
    fontSize: 20,
    color: Colors.digitYellow,
  },
});

export default ProcessRawOutput;
