import React, { Component } from "react";
import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";
import PI from "./src/PI";
import ThankYou from "./src/Screens/ThankYou";
import Header from "./src/Screens/Header";
import DocumentUpload from "./src/common/DocumentUpload";
import { Provider as PaperProvider, DefaultTheme } from "react-native-paper";
import { navigationRef } from "./src/common/RootNavigation";
import { Provider } from "react-redux";
import store from "./src/redux/store";
import Progress from "./src/Screens/Progress";
// import Tutorial from "./src/Screens/Tutorial";
import Camera from "./src/Screens/Camera";
import PreviewImage from "./src/Screens/PreviewImage";
import Orientation from "../../node_modules/react-native-orientation";
import Toturial from "./src/Screens/Toturial";
import InvalidImages from "./src/Screens/InvalidImages";
import Geolocation from "react-native-geolocation-service";
import Database from "../../Components/common/Database";
import Upload from "react-native-background-upload";

// Localization
const { setI18nConfig, translate } = require("./src/common/localize/i18n");
let realm = Database.getRealm();

import * as RNLocalize from "react-native-localize";
import WithQuote from "./src/Screens/WithQuote";
import WithoutQuoteScreen from "react-native-digitcamera/src/Screens/WithoutQuoteScreen";
import { PermissionsAndroid } from "react-native";
import { SELFSURVEYSERVICE_DOCUMENT_URL } from "react-native-digitcamera/lib/commonjs/Api/ApiUrls";

class App extends Component {
  constructor(props) {
    super(props);
    setI18nConfig();
  }
  componentDidMount() {
    this.setState();
    // this.test()
    this.getPermission();
    this.requestLocationPermission();
    Orientation.lockToPortrait();
    RNLocalize.addEventListener("change", this.handleLocalizationChange);
  }
  componentWillUnmount() {
    RNLocalize.removeEventListener("change", this.handleLocalizationChange);
  }

  //   test(){
  // try {
  //   console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
  //   const options = {
  //   url: SELFSURVEYSERVICE_DOCUMENT_URL,
  //   path: '/data/user/0/com.godigit.posp/cache/ReactNative-snapshot-image6318058595570040490.jpg',
  //   method: 'POST',
  //   maxRetries: 2, // set retry count (Android only). Default 2
  //   headers: {
  //         'Content-Type': 'multipart/form-data',
  //   },
  //   // Below are options only supported on Android
  //   notification: {
  //     enabled: true
  //   },
  //   useUtf8Charset: true,
  //   field: 'uploaded_media',
  //   type: 'multipart',
  //   parameters:{
  //     name:"1302024_FS.jpg",
  //     fileName:"1302024_FS",
  //     type:'image/jpeg',
  //     documentUploadData :JSON.stringify({
  //       activityId: "1302024",
  //       geoLocation: {
  //         isBlocked: 'false',
  //         deviceName: "",
  //         latitude: "",
  //         longitude:"",
  //         operatingSystem: "",
  //         timezone: '',
  //         deviceTime: "",
  //         ipAddress: "",
  //         deviceIMEI: "",
  //         macAddress: "",
  //       },
  //       isLast: "false",
  //       isLastDocument: "false",
  //     })
  //   }
  // }

  // Upload.startUpload(options).then((uploadId) => {
  //   console.log('Upload started')
  //   Upload.addListener('progress', uploadId, (data) => {
  //     console.log(`Progress: ${data.progress}%`)
  //   })
  //   Upload.addListener('error', uploadId, (data) => {
  //     console.log(`Error: ${data.error}%`)
  //   })
  //   Upload.addListener('cancelled', uploadId, (data) => {
  //     console.log(`Cancelled!`)
  //   })
  //   Upload.addListener('completed', uploadId, (data) => {
  //     // data includes responseCode: number and responseBody: Object
  //     console.log('Completed!',data)
  //   })
  // }).catch((err) => {
  //   console.log('Upload error!', err)
  // })

  // } catch (error) {
  //   console.log("ERROR ",error);
  // }
  //   }

  async getPermission() {
    const grantedCamera = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.CAMERA
    );
    const grantedAudio = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.RECORD_AUDIO
    );
    const grantedLocation = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
    );
    const grantedWrite = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
    );
    const grantedRead = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE
    );

    if (
      grantedCamera !== PermissionsAndroid.RESULTS.GRANTED ||
      grantedAudio !== PermissionsAndroid.RESULTS.GRANTED ||
      grantedLocation !== PermissionsAndroid.RESULTS.GRANTED ||
      grantedCamera !== PermissionsAndroid.RESULTS.GRANTED ||
      grantedAudio !== PermissionsAndroid.RESULTS.GRANTED
    )
      Alert.alert(translate("Permission denied"));
  }

  async requestLocationPermission() {
    if (Platform.OS === "ios") {
      this.getOneTimeLocation();
    } else {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
        );

        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          //To Check, If Permission is granted
          this.getOneTimeLocation();
        } else {
          console.log("Permission Denied");
        }
      } catch (err) {
        console.log("Error in LOCATION in Index.js", err);
      }
    }
  }

  // current location
  getOneTimeLocation() {
    Geolocation.getCurrentPosition(
      (position) => {
        console.log("AAAAAAAAAAAAAAAAA", position);

        // Saving data in realm
        realm.write(() => {
          realm.delete(realm.objects("PILocation"));
          realm.create("PILocation", {
            lat: position?.coords?.latitude.toString(),
            long: position?.coords?.longitude.toString(),
          });
        });
        var PILocation = realm.objects("PILocation");
        console.log("_____________________________________", PILocation);
      },
      (error) => {
        // See error code charts below.
        console.log(error.code, error.message);
      },
      { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
    );
  }

  handleLocalizationChange = () => {
    this.forceUpdate();
    setI18nConfig();
  };
  render() {
    const Stack = createStackNavigator();
    return (
      <NavigationContainer
        ref={navigationRef}
        theme={DefaultTheme}
        independent={true}
      >
        <PaperProvider theme={DefaultTheme}>
          <Provider store={store}>
            <Stack.Navigator screenOptions={{ headerShown: false }}>
              {this.props.props.route.params.toWithQuote == true && (
                <Stack.Screen
                  name="WithQuote"
                  component={WithQuote}
                  initialParams={this.props}
                />
              )}
              <Stack.Screen
                name="Toturial"
                component={Toturial}
                initialParams={this.props}
              />
              <Stack.Screen
                name="WithoutQuoteScreen"
                component={WithoutQuoteScreen}
                initialParams={this.props}
              />
              <Stack.Screen
                name="PI"
                component={PI}
                initialParams={this.props}
              />
              <Stack.Screen
                name="Progress"
                component={Progress}
                initialParams={this.props}
              />
              <Stack.Screen
                name="ThankYou"
                component={ThankYou}
                initialParams={this.props}
              />
              <Stack.Screen name="InvalidImages" component={InvalidImages} />
              <Stack.Screen name="Camera" component={Camera} />
              <Stack.Screen
                name="PreviewImage"
                component={PreviewImage}
                initialParams={this.props}
              />
            </Stack.Navigator>
          </Provider>
        </PaperProvider>
      </NavigationContainer>
    );
  }
}

export default App;
