import React, { useEffect, useRef, useState } from "react";
import {
  StyleSheet,
  View,
  Image,
  Text,
  BackHandler,
  ScrollView,
  Alert,
  StatusBar,
  Platform,
  Dimensions,
} from "react-native";
import {
  ANDROID_REQUEST,
  WEB_REQUEST,
} from "react-native-digitcamera/src/common/Constants";
import { translate } from "react-native-digitcamera/src/common/localize/i18n";
import Orientation from "../../../react-native-orientation";
import Geolocation from "@react-native-community/geolocation";
import { getTimeZone } from "react-native-localize";
import { TouchableOpacity } from "react-native-gesture-handler";
import RNFetchBlob from "rn-fetch-blob";
import { SELFSURVEYSERVICE_DOCUMENT_URL } from "react-native-digitcamera/src/Api/ApiUrls";
import ViewShot, { captureRef } from "react-native-view-shot";
import Carousel, { Pagination } from "react-native-snap-carousel";
import Header from "../Screens/Header";
import { PrimaryButton, Spinner } from "../common/ThemedComponents";
import Database from "../../../../Components/common/Database";
let realm = Database.getRealm();
import { measureConnectionSpeed } from "react-native-network-bandwith-speed";
import { instructionData } from "react-native-digitcamera/src/common/Services/instruction";
import { dispatch } from "react-native-digitcamera/src/common/RootNavigation";
import { useDispatch } from "react-redux";
import {
  firebaseAttributes,
  errorRecord,
  firebaseEvents,
} from "../common/libEventLog/libCrashlytics/libCrashlyticsEvent";
import { async } from "validate.js";
import {
  startCapturingSensorData,
  cleanSensorDataArr,
  unsubscribeSensors,
} from "../common/SensorData";
import UserExperior from "react-native-userexperior/UserExperior";

const not_blur = require("../common/Image/not_blur.png");
const open_area_good_light = require("../common/Image/open_area_good_light.png");
const maintain_distance = require("../common/Image/maintain_distance.png");
const rc_book = require("../common/Image/rc_book.png");
const instruction = require("../common/Image/instruction.png");
const iOS = Platform.OS === "ios";
var RealmCustomerDetails = realm.objects("CustomerDetails");

import {
  UELogEvent,
  UELogMessage,
} from "../common/libEventLog/UserExperior/LibUserExperior";
import Colors from "react-native-digitcamera/src/common/Colors";
import { traceUserMobile } from "../../../../Components/common/Trace";
let instuction = [];
var activityId,
  activityTypeId,
  licensePlateNumber,
  toWithQuote,
  toTutorial,
  quoteNumber;
const Toturial = ({ navigation, route }) => {
  /*
  using React.createRef() instead of useRef.
  Potential Bug fix for 
  Invariant Violation: Argument appears to not be a ReactComponent, keys: current  
  https://stackoverflow.com/questions/54939413/invariant-violation-argument-appears-to-not-be-a-reactcomponent
  */ 
  const nextcarousel = React.createRef();
  const [currentIndex, SetCurrentIndex] = useState(0);
  const [toturialData, setToturialData] = useState([]);
  const [isLoading, SetIsLoading] = useState(true);
  const [, updateState] = React.useState();
  /* @NEWORDER */
  const forceUpdate = React.useCallback(() => updateState({}), []);

  var RealmCustomerDetails = realm.objects("CustomerDetails");

  var DataSpeed;

  /*@NEWORDER*/
  const { fromRCB } = route.params;
  const dispatch = useDispatch();

  useEffect(() => {
    // analytics logs
    traceUserMobile(RealmCustomerDetails[0]?.mobileNumber);
    if (fromRCB !== undefined && fromRCB) {
      setToturialData([
        {
          image: open_area_good_light,
          heading: "Before filming the video, please make sure: ",
          subHeading: [
            { points: "You leave 5-6ft space around your vehicle" },
            { points: "Your vehicle is parked in an area with good light" },
            { points: "Your vehicle is clean" },
          ],
        },
        {
          image: instruction,
          heading: "While filming the video, please make sure:",
          subHeading: [
            {
              points: "Complete vehicle is visible on the screen at all times",
            },
            { points: "Move your device slowly to avoid blur" },
          ],
        },
      ]);
    }
  }, [fromRCB]);

  console.log("^^^^^^^^^^^ FROM RCBB", fromRCB);

  /* Get max dimension for screen width */
  const getMaxWidth = () => {
    return Math.round(
      Math.min(Dimensions.get("screen").height, Dimensions.get("screen").width)
    );
  };

  /*Initial SCREEN_WIDTH*/
  let SCREEN_WIDTH = getMaxWidth();

  useEffect(() => {
    if (!iOS) {
      const Immersive = require("react-native-immersive").Immersive;
      Immersive.setImmersive(false);
    }
    StatusBar.setTranslucent(false);
    Orientation.lockToPortrait();
    /* Incase if there is orientation change */
    SCREEN_WIDTH = getMaxWidth();

    var RealmData = realm.objects("PIVechicleData");
    (activityId = RealmData[0].activityId),
      (activityTypeId = RealmData[0].activityTypeId),
      (licensePlateNumber = RealmData[0].licensePlateNumber),
      (toWithQuote = RealmData[0].toWithQuote),
      (toTutorial = RealmData[0].toTutorial),
      (quoteNumber = RealmData[0].quoteNumber),
      console.log(
        "!!!!!!!!!!!!!!!!!!!!!!!!",
        activityId,
        activityTypeId,
        licensePlateNumber,
        toWithQuote,
        toTutorial,
        quoteNumber
      );
    getInstruction();
    // setTutorialData(activityTypeId);
    let unsubscribe = navigation.addListener("focus", () => {
      Orientation.lockToPortrait();
      /* Incase if there is orientation change */
      SCREEN_WIDTH = getMaxWidth();
      if (!iOS) {
        const Immersive = require("react-native-immersive").Immersive;
        Immersive.setImmersive(false);
      }
    });
    saveToRealm();

    // dynatrace
    traceUserMobile(RealmCustomerDetails[0]?.mobileNumber);

    return () => {
      unsubscribe();
      cleanSensorDataArr();
      unsubscribeSensors();
    };
  }, []);

  /* setQuickTips */
  const setQuickTips = (hasRCB) => {
    /* 
      if instructions has rcb, render rcb tips
      if navigated here from rcb, then render video tips
      if instructions doesnt have rcb, then render video tips
    */

    if (activityTypeId === 5 || activityTypeId === 63) {
      if (hasRCB) {
        setToturialData([
          {
            image: rc_book,
            heading:
              "Keep your vehicle’s Registration Certificate (RC Book/Card) handy",
            subHeading: [],
          },
        ]);
      } else if ((fromRCB !== undefined && fromRCB) || !hasRCB) {
        setToturialData([
          {
            image: open_area_good_light,
            heading: "Before filming the video, please make sure: ",
            subHeading: [
              { points: "You leave 5-6ft space around your vehicle" },
              { points: "Your vehicle is parked in an area with good light" },
              { points: "Your vehicle is clean" },
            ],
          },
          {
            image: instruction,
            heading: "While filming the video, please make sure:",
            subHeading: [
              {
                points:
                  "Complete vehicle is visible on the screen at all times",
              },
              { points: "Move your device slowly to avoid blur" },
            ],
          },
        ]);
      }
    } else {
      setToturialData([
        {
          image: open_area_good_light,
          heading: "Before recording the video please make sure :",
          subHeading: [
            { points: "Your vehicle is in an open space with good light" },
            { points: "Your vechicle is clean" },
            // { points: "Your device camera lens is clean" },
          ],
        },
        // {
        //   image: maintain_distance,
        //   heading: "While clicking the images, please make sure:",
        //   subHeading: [
        //     { points: "You maintain 4-5 feet distance from your vehicle" },
        //     { points: "Edges of the vehicle are also captured in the images" },
        //     { points: "Captured images are not blurred" },
        //   ],
        // },
        {
          image: rc_book,
          heading:
            "Keep your vehicle’s Registration Certificate (RC Book/Card) handy",
          subHeading: [],
        },
        {
          image: instruction,
          heading:
            "To help you click the correct image, simply refer to the image and instructions given at each step and you will be done in no time!",
          subHeading: [],
        },
      ]);
    }
  };

  // const setTutorialData = (activityTypeId) => {
  //   console.log("ACTTTTTTTTTTTTTTTTT ", activityTypeId);
  //   if (activityTypeId == 5) {
  //     /*@NEWORDER*/

  //     setToturialData([
  //       {
  //         image: rc_book,
  //         heading:
  //           "Keep your vehicle’s Registration Certificate (RC Book/Card) handy",
  //         subHeading: [],
  //       },
  //     ]);
  //   } else {
  //     setToturialData([
  //       {
  //         image: open_area_good_light,
  //         heading: "Before recording the video please make sure :",
  //         subHeading: [
  //           { points: "Your vehicle is in an open space with good light" },
  //           { points: "Your vechicle is clean" },
  //           // { points: "Your device camera lens is clean" },
  //         ],
  //       },
  //       // {
  //       //   image: maintain_distance,
  //       //   heading: "While clicking the images, please make sure:",
  //       //   subHeading: [
  //       //     { points: "You maintain 4-5 feet distance from your vehicle" },
  //       //     { points: "Edges of the vehicle are also captured in the images" },
  //       //     { points: "Captured images are not blurred" },
  //       //   ],
  //       // },
  //       {
  //         image: rc_book,
  //         heading:
  //           "Keep your vehicle’s Registration Certificate (RC Book/Card) handy",
  //         subHeading: [],
  //       },
  //       {
  //         image: instruction,
  //         heading:
  //           "To help you click the correct image, simply refer to the image and instructions given at each step and you will be done in no time!",
  //         subHeading: [],
  //       },
  //     ]);
  //   }
  // };

  const saveToRealm = () => {
    try {
      realm.write(() => {
        realm.delete(realm.objects("PIRCBCount"));

        realm.create("PIRCBCount", {
          addMoreCount: 2,
        });
      });

      realm.write(() => {
        realm.delete(realm.objects("PIclickedCount"));

        realm.create("PIclickedCount", {
          clickedCount: 0,
        });
      });

      realm.write(() => {
        realm.delete(realm.objects("PIUploadedCount"));

        realm.create("PIUploadedCount", {
          uploadedCount: 0,
        });
      });
    } catch (error) {
      console.log("Error", error);
    }
  };

  // check type of request
  const instructionWebOrAndroid = (activityTypeId) => {
    activityTypeId = getActivityTypeIdIfSSL(activityTypeId);
    return activityTypeId == 6 ||
      activityTypeId == 7 ||
      activityTypeId == 8 ||
      activityTypeId == 9 ||
      activityTypeId == 10 ||
      activityTypeId == 11 ||
      activityTypeId == 15 ||
      activityTypeId == 31
      ? WEB_REQUEST
      : ANDROID_REQUEST;
  };

  // get ssl
  const getActivityTypeIdIfSSL = (activityTypeId) => {
    if (activityTypeId == 50) {
      // Used for SSL deeplink / mapping given by Gowtham
      activityTypeId = 5;
    } else if (activityTypeId == 49) {
      activityTypeId = 26;
    } else if (activityTypeId == 51) {
      activityTypeId = 30;
    }
    return activityTypeId;
  };

  const subscribeSensorData = () => {};

  // get vechicle instructions
  const getInstruction = async () => {
    try {
      UELogEvent("getInstruction Started..", {
        "Activity Type Id": activityTypeId,
      });
      let requestTypeName = instructionWebOrAndroid(activityTypeId);
      UELogMessage("Response from instructionWebOrAndroid", {
        "Request Type Name": JSON.stringify(requestTypeName),
      });
      let requestTypeValue;
      if (requestTypeName == WEB_REQUEST) {
        requestTypeValue = 1;
      } else {
        requestTypeValue = 0;
      }

      UELogEvent("instructionData service call started", {
        "Type Id": JSON.stringify(activityTypeId),
        "Request Value": JSON.stringify(requestTypeValue),
      });
      let V_instuction = await instructionData({
        typeId: activityTypeId,
        requestValue: requestTypeValue,
        activityId: activityId,
      });
      if (activityTypeId == 5 || activityTypeId == 63) {
        // if(__DEV__){
        //   Alert.alert("We are using pre-defined data")
        // }
        //V_instuction = JSON.parse(
        // '{"videoInspectionResponse":{"blockedSource":{"value":"NA"},"isEligible":{"value":true}},"surveyMasterId":32,"activityTypeId":5,"createdDate":"May 20, 2022 02:42:33 PM","description":"We have made this quick and simple","lastModifiedDate":"May 20, 2022 02:42:33 PM","noOfSteps":4,"title":"A few tips for your 4 wheeler video inspection","TSurveyInstructions":[{"surveyInstructionsId":1740,"createdDate":"May 18, 2022 12:25:18 PM","instructionData":"Take a picture of the front of your RC book/card.","lastModifiedDate":"May 18, 2022 12:25:18 PM","instructionTime":1,"instructionDataHn":"अपनी आरसी बुक/कार्ड के सामने की तस्वीर लें।","effectiveDate":"May 18, 2022 12:27:19 PM","displayorder":"1","type":""},{"surveyInstructionsId":1744,"createdDate":"May 18, 2022 12:30:48 PM","instructionData":"Take some time \u0026 locate your chassis number","lastModifiedDate":"May 18, 2022 12:30:48 PM","instructionTime":3,"instructionDataHn":"कुछ समय निकालें और अपना चेसिस नंबर खोजें","effectiveDate":"May 18, 2022 12:32:26 PM","instructionTitle":"Find your chassis number","okButtonText":"I have found the chassis no.","instructionAssests":"https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/chassis_find.png","displayorder":"5","type":"image"},{"surveyInstructionsId":1742,"createdDate":"May 18, 2022 12:30:48 PM","instructionData":"We\u0027ll record inside the engine bay so make sure the bonnet is kept open.","lastModifiedDate":"May 18, 2022 12:30:48 PM","instructionTime":3,"instructionDataHn":"हम इंजन बे के अंदर रिकॉर्ड करेंगे इसलिए सुनिश्चित करें कि बोनट खुला रखा गया है","effectiveDate":"May 18, 2022 12:32:26 PM","instructionTitle":"Please open the bonnet of the car","okButtonText":"I have opened the bonnet","instructionAssests":"https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/open_bonnet.png","displayorder":"3","type":"image"},{"surveyInstructionsId":1743,"createdDate":"May 18, 2022 12:30:48 PM","instructionData":"The engine should be ON throughout the inspection.","lastModifiedDate":"May 18, 2022 12:30:48 PM","instructionTime":3,"instructionDataHn":"पूरे निरीक्षण के दौरान इंजन चालू रहना चाहिए","effectiveDate":"May 18, 2022 12:32:26 PM","instructionTitle":"Start your vehicle","okButtonText":"I have started the vehicle","instructionAssests":"https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/key_start.png","displayorder":"4","type":"image"},{"surveyInstructionsId":1745,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"What is embossed chassis no.?","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"What is embossed chassis no.?","displayorder":"6","type":"image"},{"surveyInstructionsId":1746,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"What is embossed chassis no.?","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"What is embossed chassis no.?","displayorder":"7","type":"image"},{"surveyInstructionsId":1747,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Make sure the chassis number is visible on the screen","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"8","type":"instruction"},{"surveyInstructionsId":1748,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Make sure all the doors are closed.","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"9","type":"instruction"},{"surveyInstructionsId":1741,"createdDate":"May 18, 2022 12:25:18 PM","instructionData":"Take a picture of the back of your RC book/card.","lastModifiedDate":"May 18, 2022 12:25:18 PM","instructionTime":2,"instructionDataHn":"अपनी आरसी बुक/कार्ड के पीछे की तस्वीर लें।","effectiveDate":"May 18, 2022 12:27:19 PM","displayorder":"2","type":""},{"surveyInstructionsId":1749,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Face the front of the car","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"10","type":"instruction"},{"surveyInstructionsId":1750,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Let’s look inside the engine bay","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"11","type":"instruction"},{"surveyInstructionsId":1751,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Face the front of the car","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"12","type":"instruction"},{"surveyInstructionsId":1752,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Number plate \u0026 front winshield should be visible","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"13","type":"instruction"},{"surveyInstructionsId":1753,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Move towards the front passenger side","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"14","type":"instruction"},{"surveyInstructionsId":1754,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Ensure the full car is in the frame","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"15","type":"instruction"},{"surveyInstructionsId":1755,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Complete side of the car should be seen","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"16","type":"instruction"},{"surveyInstructionsId":1756,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Step back if you need to fit the car in the frame","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"17","type":"instruction"},{"surveyInstructionsId":1757,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Move to the back of the car","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"18","type":"instruction"},{"surveyInstructionsId":1764,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"All corners of the windshield should be filmed from inside","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"25","type":"instruction"},{"surveyInstructionsId":1765,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Let’s take a look at the odometer","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"26","type":"instruction"},{"surveyInstructionsId":1761,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Move to the front of the car","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"22","type":"instruction"},{"surveyInstructionsId":1762,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Move closer to the windshield","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"23","type":"instruction"},{"surveyInstructionsId":1763,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Please sit on the driver\u0027s seat","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"24","type":"instruction"},{"surveyInstructionsId":1758,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Number plate \u0026 back windshield should be visible","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"19","type":"instruction"},{"surveyInstructionsId":1759,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Move to the driver’s side","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"20","type":"instruction"},{"surveyInstructionsId":1760,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Complete side of the car should be visible","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"21","type":"instruction"}],"TSurveySteps":[{"surveyStepsId":1053,"createdDate":"Feb 21, 2020 12:15:05 PM","isLast":false,"lastModifiedDate":"Feb 21, 2020 12:15:05 PM","stepAssests":"https://cdn.godigit.com/digitEdgeAssets/Motor/4W_PI_RCB1_V2.jpg","stepStencilAssests":"","stepTitle":"RC Book/Card","stepTitleHn":"आरसी बुक/कार्ड","imageName":"RCB1","displayOrder":160,"type":"image","TSurveyInstructions":[{"surveyInstructionsId":1740,"createdDate":"May 18, 2022 12:25:18 PM","instructionData":"Take a picture of the front of your RC book/card.","lastModifiedDate":"May 18, 2022 12:25:18 PM","instructionTime":1,"instructionDataHn":"अपनी आरसी बुक/कार्ड के सामने की तस्वीर लें।","effectiveDate":"May 18, 2022 12:27:19 PM","displayorder":"1","type":""}],"effectiveDate":"Dec 17, 2022 03:18:48 PM"},{"surveyStepsId":1054,"createdDate":"Feb 21, 2020 12:15:05 PM","description":"Make sure the engine is on while taking the odometer km reading","isLast":false,"descriptionHn":"सुनिश्चित करें कि ओडोमीटर किमी रीडिंग लेते समय इंजन चालू है","lastModifiedDate":"Feb 21, 2020 12:15:05 PM","stepAssests":"https://cdn.godigit.com/digitEdgeAssets/Motor/MZBG2T7_Odometer-01_V2.jpg","stepStencilAssests":"","stepTitle":"Please enter the odometer km reading","stepTitleHn":"कृपया ओडोमीटर किमी रीडिंग दर्ज करें","imageName":"DBD","displayOrder":205,"type":"input","TSurveyInstructions":[],"effectiveDate":"Dec 17, 2022 03:18:48 PM"},{"surveyStepsId":1055,"createdDate":"Feb 21, 2020 12:15:05 PM","description":"Shoot video from a distance to capture the entire vehicle","isLast":false,"descriptionHn":"पूरीगाड़ी को फ़ोकस करने के लिए दूर से वीडियो शूट करें","lastModifiedDate":"Feb 21, 2020 12:15:05 PM","stepAssests":"https://d2h44aw7l5xdvz.cloudfront.net/videos/self-inspection-for-car.mp4","stepStencilAssests":"","stepTitle":"Take a 360° video","stepTitleHn":"360 ° वीडियो लें \"","imageName":"VDO","displayOrder":220,"type":"video","TSurveyInstructions":[{"surveyInstructionsId":1742,"createdDate":"May 18, 2022 12:30:48 PM","instructionData":"We\u0027ll record inside the engine bay so make sure the bonnet is kept open.","lastModifiedDate":"May 18, 2022 12:30:48 PM","instructionTime":3,"instructionDataHn":"हम इंजन बे के अंदर रिकॉर्ड करेंगे इसलिए सुनिश्चित करें कि बोनट खुला रखा गया है","effectiveDate":"May 18, 2022 12:32:26 PM","instructionTitle":"Please open the bonnet of the car","okButtonText":"I have opened the bonnet","instructionAssests":"https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/open_bonnet.png","displayorder":"3","type":"image"},{"surveyInstructionsId":1743,"createdDate":"May 18, 2022 12:30:48 PM","instructionData":"The engine should be ON throughout the inspection.","lastModifiedDate":"May 18, 2022 12:30:48 PM","instructionTime":3,"instructionDataHn":"पूरे निरीक्षण के दौरान इंजन चालू रहना चाहिए","effectiveDate":"May 18, 2022 12:32:26 PM","instructionTitle":"Start your vehicle","okButtonText":"I have started the vehicle","instructionAssests":"https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/key_start.png","displayorder":"4","type":"image"},{"surveyInstructionsId":1744,"createdDate":"May 18, 2022 12:30:48 PM","instructionData":"Take some time \u0026 locate your chassis number","lastModifiedDate":"May 18, 2022 12:30:48 PM","instructionTime":3,"instructionDataHn":"कुछ समय निकालें और अपना चेसिस नंबर खोजें","effectiveDate":"May 18, 2022 12:32:26 PM","instructionTitle":"Find your chassis number","okButtonText":"I have found the chassis no.","instructionAssests":"https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/chassis_find.png","displayorder":"5","type":"image"},{"surveyInstructionsId":1745,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"What is embossed chassis no.?","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"What is embossed chassis no.?","displayorder":"6","type":"image"},{"surveyInstructionsId":1746,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"What is embossed chassis no.?","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"What is embossed chassis no.?","displayorder":"7","type":"image"},{"surveyInstructionsId":1747,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Make sure the chassis number is visible on the screen","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"8","type":"instruction"},{"surveyInstructionsId":1748,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Make sure all the doors are closed.","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"9","type":"instruction"},{"surveyInstructionsId":1749,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Face the front of the car","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"10","type":"instruction"},{"surveyInstructionsId":1750,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Let’s look inside the engine bay","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"11","type":"instruction"},{"surveyInstructionsId":1751,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Face the front of the car","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"12","type":"instruction"},{"surveyInstructionsId":1752,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Number plate \u0026 front winshield should be visible","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"13","type":"instruction"},{"surveyInstructionsId":1753,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Move towards the front passenger side","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"14","type":"instruction"},{"surveyInstructionsId":1754,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Ensure the full car is in the frame","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"15","type":"instruction"},{"surveyInstructionsId":1755,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Complete side of the car should be seen","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"16","type":"instruction"},{"surveyInstructionsId":1756,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Step back if you need to fit the car in the frame","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"17","type":"instruction"},{"surveyInstructionsId":1757,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Move to the back of the car","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"18","type":"instruction"},{"surveyInstructionsId":1758,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Number plate \u0026 back windshield should be visible","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"19","type":"instruction"},{"surveyInstructionsId":1759,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Move to the driver’s side","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"20","type":"instruction"},{"surveyInstructionsId":1760,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Complete side of the car should be visible","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"21","type":"instruction"},{"surveyInstructionsId":1761,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Move to the front of the car","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"22","type":"instruction"},{"surveyInstructionsId":1762,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Move closer to the windshield","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"23","type":"instruction"},{"surveyInstructionsId":1763,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Please sit on the driver\u0027s seat","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"24","type":"instruction"},{"surveyInstructionsId":1764,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"All corners of the windshield should be filmed from inside","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"25","type":"instruction"},{"surveyInstructionsId":1765,"createdDate":"May 31, 2022 02:40:44 PM","instructionData":"Let’s take a look at the odometer","lastModifiedDate":"May 31, 2022 02:40:44 PM","instructionTime":2,"effectiveDate":"May 31, 2022 02:40:44 PM","instructionTitle":"","displayorder":"26","type":"instruction"}],"effectiveDate":"Dec 17, 2022 03:18:48 PM"},{"surveyStepsId":1056,"createdDate":"Feb 21, 2020 12:15:05 PM","isLast":false,"lastModifiedDate":"Feb 21, 2020 12:15:05 PM","stepAssests":"https://cdn.godigit.com/digitEdgeAssets/Motor/4W_PI_RCB2_V2.jpg","stepStencilAssests":"","stepTitle":"RC Book/Card","stepTitleHn":"आरसी बुक/कार्ड","imageName":"RCB2","displayOrder":180,"type":"image","TSurveyInstructions":[{"surveyInstructionsId":1741,"createdDate":"May 18, 2022 12:25:18 PM","instructionData":"Take a picture of the back of your RC book/card.","lastModifiedDate":"May 18, 2022 12:25:18 PM","instructionTime":2,"instructionDataHn":"अपनी आरसी बुक/कार्ड के पीछे की तस्वीर लें।","effectiveDate":"May 18, 2022 12:27:19 PM","displayorder":"2","type":""}],"effectiveDate":"Dec 17, 2022 03:18:48 PM"}],"isWebRequest":2,"titleHn":"आपके 4 व्हीलर इंस्पेक्शन के लिए कुछ सुझाव","descriptionHn":"हमने इसे शीघ्र होने वाला और सरल बना दिया है फ़ोटोको क्लिक करने से पहले:"}'
        // );
      }
      UELogMessage("Response from instruction data", {
        "Vehicle Instructions": JSON.stringify(V_instuction),
      });

      // DataSpeed = await measureConnectionSpeed();
      if (true) {
        // if (false) {
        instuction = [];
        console.log("**** instruction: before");
        V_instuction?.TSurveySteps.map((item) => {
          if (
            activityTypeId === 26 &&
            V_instuction?.stencilAssets !== undefined
          ) {
            /*adding stencil assets to instructions*/
            const stencilItem = V_instuction?.stencilAssets.find(
              (asset) => asset.poseName === item.imageName
            );
            // UELogEvent("Toturial, fetching stencil data for 2w from V_instructions", {
            //   "stencilItem": JSON.stringify(stencilItem)
            // })
            console.log("^^^^^^^^ STENCIL ITEM OBJ........", stencilItem);
            if (stencilItem !== undefined) {
              const stencilAssetURI = stencilItem.stencilAssetLink;
              item["stepStencilAssests"] = stencilAssetURI;
            }
          }

          console.log("**** instruction: added");
          instuction.push(item);
        });

        // setQuickTips
        const rcbObj = instuction.find((element) => {
          return element.imageName.includes("RCB");
        });
        if (rcbObj) {
          setQuickTips(true);
        } else {
          setQuickTips(false);
        }
      } else {
        instuction = [];
        V_instuction?.TSurveySteps.map((item) => {
          if (item.imageName != "VDO") {
            instuction.push(item);
          }
        });
      }
      // sorting instructions
      instuction.sort((obj1, obj2) => {
        let id1 = obj1.displayOrder;
        let id2 = obj2.displayOrder;
        return id1 - id2;
      });

      // New requirement -> Video shoot should be bring to first
      // if (instuction.length > 0) {
      //   let vdoObj = instuction[instuction.length - 1];
      //   instuction.splice(0, 0, vdoObj);
      //   instuction.pop();
      // }

      realm.write(() => {
        realm.delete(realm.objects("PIVechicleInstruction"));
        realm.create("PIVechicleInstruction", {
          instuction: JSON.stringify(instuction),
        });
        var RealmInstructionData = realm.objects("PIVechicleInstruction");
        console.log(
          "^^^^^^^^^^^^^^^^^^^^^^^^^ ",
          JSON.parse(RealmInstructionData[0].instuction).length
        );
      });
      setTimeout(() => {
        SetIsLoading(false);
      }, 1000);
      UELogMessage("Instrutions Details", {
        "Request Type Value": JSON.stringify(requestTypeValue),
        "Activity Id": JSON.stringify(activityId),
        "Activity Type Id": JSON.stringify(activityTypeId),
      });
      firebaseEvents(
        "Instruction",
        { requestTypeValue: requestTypeValue },
        activityId,
        activityTypeId,
        ""
      );
    } catch (error) {
      UELogEvent("getInstructions stopped in catch", {
        Error: JSON.stringify(error),
      });
      firebaseAttributes(error);
      errorRecord(error);
      console.log("Error in Tutorial >>> ", error);
      Alert.alert(
        "Oops! Unable to proceed",
        "We are experiencing technical issue, Please try after sometime. Or Still You can continue with registration number"
      );
      setTimeout(() => {
        SetIsLoading(false);
      }, 1000);
    }
  };

  /* @MOVETORCB */
  const moveToRCBPreview = () => {
    const rcbObj = instuction.find((element) => {
      return element.imageName.includes("RCB");
    });
    // UELogEvent("Starting videopi flow with RCB", {
    //   "rcbObj": JSON.stringify(rcbObj)
    // })
    // const rcbObj = undefined;
    /*@NEWORDER*/
    if (rcbObj && fromRCB === undefined) {
      console.log("^^^^^^^ moveToRCBPreview, rcbObj ^^^^^^^", rcbObj);

      /* Clear all RCB Redux Data */
      dispatch({
        type: "CLEAR_RCB_DATA",
      });
      console.log("^^^Tutorial, Cleared RCB Data from redux");
      navigation.navigate("RCBPreviewScreen", {
        proceedCallback: () => {
          moveNow();
        },
      });
    } else if (fromRCB !== undefined && fromRCB) {
      // UELogEvent("Starting videopi flow directly to VDO & ODO")
      /* Directly taking to enter odometer reading then show demo video */
      moveToCamera();
      /* if rcb is not required then move to video directly */
      // moveToCamera()
    } else if (rcbObj == undefined) {
      // UELogEvent("Starting videopi flow directly to VDO & ODO")
      moveToCamera();
    }
  };

  const moveToCamera = () => {
    const demoVideoUriObj = instuction.find((element) => {
      return element.imageName === "VDO";
    });
    UELogEvent("Toturial, moveToCamera, demoVideoUriObj", {
      DemoVideoUriObj: JSON.stringify(demoVideoUriObj),
    });
    if (demoVideoUriObj) {
      const demoVideoUri = demoVideoUriObj?.stepAssests;
      console.log("*** moveToCamera demoVideoUri: " + demoVideoUri);
      navigation.navigate("DemoVideo", {
        videoUri: demoVideoUri,
        onSkip: () => {
          navigation.navigate("Camera", {
            activityId,
            activityTypeId,
            licensePlateNumber,
            toVDO: true /* @NEWORDER */,
          });
        },
        onProceed: () => {
          navigation.navigate("Camera", {
            activityId,
            activityTypeId,
            licensePlateNumber,
            toVDO: true /* @NEWORDER */,
          });
        },
      });
    }
  };

  const moveNow = () => {
    navigation.navigate("Camera", {
      activityId,
      activityTypeId,
      licensePlateNumber,
    });
  };

  const _renderToturial = ({ item, index }) => {
    return (
      <View style={{ margin: 24, flex: 1 }}>
        <ScrollView>
          {/* Image view */}
          <View style={styles.imageView}>
            <Image
              source={item.image}
              resizeMode="contain"
              style={{
                width: SCREEN_WIDTH - SCREEN_WIDTH * 0.5,
                height: SCREEN_WIDTH - SCREEN_WIDTH * 0.5,
                alignSelf: "center",
                resizeMode: "contain",
              }}
            />
          </View>
          {/* info View */}
          <View style={styles.InfoView}>
            {/* <Text style={styles.headingText}>{translate(item.heading)}</Text> */}
            <Text style={styles.headingText}>{item.heading}</Text>
            {item.subHeading?.map((item, index) => {
              return (
                <View
                  style={{ flexDirection: "row", alignItems: "flex-start" }}
                >
                  <Text key={"" + index} style={styles.pointStyle}>
                    {"\u2022"}
                  </Text>

                  <View>
                    <Text style={styles.pointText}>{"" + item.points}</Text>
                  </View>
                </View>
              );
            })}
          </View>
        </ScrollView>
        <View>
          <Pagination
            dotsLength={toturialData.length}
            activeDotIndex={index}
            containerStyle={{ alignContent: "flex-end" }}
            dotStyle={{
              width: 11,
              height: 6,
              borderRadius: 5,
              marginHorizontal: 6,
              backgroundColor: "#000000",
            }}
            inactiveDotStyle={{
              // Define styles for inactive dots here
              width: 6,
              height: 6,
              borderRadius: 5,
              marginHorizontal: 6,
              backgroundColor: "#DDDDDD",
            }}
            inactiveDotOpacity={0.4}
            inactiveDotScale={0.6}
          />
        </View>
      </View>
    );
  };
  return (
    <View style={styles.main}>
      <Spinner loading={isLoading} />
      <Header
        showTitle={"Quick Tips"}
        hideArrowBackButton={false}
        onlanguagechange={() => {
          forceUpdate();
        }}
        onbackPress={() => {
          try {
            console.log("navigation.canGoBack()", navigation.canGoBack());
            if (navigation.canGoBack()) {
              navigation.pop();
            } else {
              if (Platform.OS === "android") {
                Alert.alert("Close", "are you sure ?", [
                  {
                    text: "Yes",
                    onPress: () => {
                      BackHandler.exitApp();
                    },
                    style: "cancel",
                  },
                  {
                    text: "No",
                    onPress: () => {
                      console.log("on No pressed");
                    },
                  },
                ]);
              }
            }
          } catch (error) {}
        }}
      />

      <View style={{ flex: 0.9 }}>
        <Carousel
          ref={nextcarousel}
          data={toturialData}
          renderItem={_renderToturial}
          sliderWidth={SCREEN_WIDTH}
          itemWidth={SCREEN_WIDTH}
          autoplay={false}
          loop={false}
          onBeforeSnapToItem={(index) => {
            SetCurrentIndex(index);
          }}
        />
      </View>
      <View
        style={{
          marginLeft: 24,
          marginRight: 24,
          width: SCREEN_WIDTH - 48,
          height: 1,
          backgroundColor: "#F5F5F5",
        }}
      />
      {currentIndex == toturialData.length - 1 ? (
        <View
          style={{
            flex: 0.1,
            justifyContent: "center",
            marginLeft: 24,
            marginRight: 24,
          }}
        >
          <PrimaryButton
            onPress={() => {
              if (instuction === undefined || instuction.length <= 0) {
                Alert.alert(
                  "Oops! ",
                  "We are unable to fetch guiding instruction for you, please try again"
                );
                if (navigation.canGoBack()) {
                  navigation.pop();
                } else {
                  /* handled crashed on OEM dealer */
                  if (route.params.props.navigation.canGoBack()) {
                    route.params.props.navigation.goBack();
                  }
                }
                return;
              }

              nextcarousel.current.snapToNext();
              if (currentIndex == toturialData.length - 1) {
                startCapturingSensorData();

                /*@OLDFLOW */
                console.log("^^^^^^^^ ACTIVITYTYPEID", activityTypeId);
                if (activityTypeId === 5 || activityTypeId === 63) {
                  // UELogEvent("Toturial, starting VideoPI flow");
                  moveToRCBPreview();
                } else {
                  // UELogEvent("Starting Old flow.")
                  navigation.navigate("PI", {
                    activityId,
                    activityTypeId,
                    licensePlateNumber,
                  });
                }
              }
              Orientation.lockToLandscape();
            }}
          >
            {"I understand"}
          </PrimaryButton>
        </View>
      ) : (
        <View style={styles.buttonView}>
          <View style={{ flex: 0.5, justifyContent: "center" }}>
            <TouchableOpacity
              onPress={() => {
                console.log("**** instuction " + instuction.length);

                if (instuction === undefined || instuction.length <= 0) {
                  Alert.alert(
                    "Oops! ",
                    "We are unable to fetch guiding instruction for you, please try again"
                  );
                  console.log("^^^ Toturial -> Alert go back");
                  if (navigation.canGoBack()) {
                    navigation.pop();
                  } else {
                    /* handled crashed on OEM dealer */
                    if (route.params.props.navigation.canGoBack()) {
                      route.params.props.navigation.goBack();
                    }
                  }
                  return;
                }

                startCapturingSensorData();
                /*@OLDFLOW */
                console.log(
                  "^^^^^^^ ACTIVITY TYPE ID ^^^^^^^^",
                  activityTypeId
                );
                if (activityTypeId === 5 || activityTypeId === 63) {
                  moveToRCBPreview();
                } else {
                  navigation.navigate("PI", {
                    activityId,
                    activityTypeId,
                    licensePlateNumber,
                  });
                }
                Orientation.lockToLandscapeLeft();
                firebaseEvents(
                  "skip_Tutorial_clicked",
                  "",
                  activityId,
                  activityTypeId,
                  ""
                );
              }}
            >
              <Text
                style={{
                  fontFamily: "Muli-Black",
                  fontSize: 14,
                  color: "#FFAA00",
                  alignSelf: "center",
                }}
              >
                {translate("SKIP TUTORIAL")}
              </Text>
            </TouchableOpacity>
          </View>
          <View style={{ flex: 0.5, justifyContent: "center" }}>
            <PrimaryButton
              onPress={() => {
                if (instuction === undefined || instuction.length <= 0) {
                  Alert.alert(
                    "Oops! ",
                    "We are unable to fetch guiding instruction for you, please try again"
                  );
                  if (navigation.canGoBack()) {
                    navigation.pop();
                  } else {
                    /* handled crashed on OEM dealer */
                    if (route.params.props.navigation.canGoBack()) {
                      route.params.props.navigation.goBack();
                    }
                  }
                  return;
                }

                nextcarousel.current.snapToNext();
                if (currentIndex == toturialData.length - 1) {
                  startCapturingSensorData();
                  moveToCamera();
                  Orientation.lockToLandscapeLeft();
                  firebaseEvents(
                    "start_clicked",
                    "",
                    activityId,
                    activityTypeId,
                    ""
                  );
                }
              }}
            >
              {currentIndex == toturialData.length - 1
                ? translate("Start")
                : translate("Next")}
            </PrimaryButton>
          </View>
        </View>
      )}
    </View>
  );
};
export default Toturial;

const styles = StyleSheet.create({
  main: {
    flex: 1,
    backgroundColor: "#FFFFFF",
  },
  imageView: {
    flex: 0.6,
    justifyContent: "center",
  },
  InfoView: {
    flex: 0.4,
  },
  headingText: {
    fontFamily: "Muli-Bold",
    fontSize: 20,
    marginBottom: 16,
    marginTop: 24,
  },
  pointText: {
    fontSize: 18,
    fontFamily: "Muli-Regular",
    lineHeight: 30,
    paddingHorizontal: 8,
  },
  buttonView: {
    flex: 0.1,
    marginLeft: 24,
    marginRight: 24,
    justifyContent: "center",
    flexDirection: "row",
  },
  pointStyle: {
    fontSize: 18,
    fontFamily: "Muli-Regular",
    lineHeight: 30,
    color: Colors.veryLightGray,
  },
});
