<commit_before>import { Button, Text, useTheme } from '@ui-kitten/components';
import * as ImagePicker from 'expo-image-picker';
import mime from 'mime';
import propTypes from 'prop-types';
import React from 'react';
import { Alert, Image, StyleSheet, View } from 'react-native';
import config from '../../services/config';
import { getIcon } from '../../services/icons';
import { ACCURACY, getLocation } from '../../services/location';
import useStyles, { PADDING } from '../../services/styles';
import { pointCoordinatesToString } from '../../services/utilities';
import Spinner from '../Spinner';

const THUMBNAIL_SIZE = 110;
export function getCoordinatesFromExif(exif) {
  if (exif?.GPSLatitude && exif?.GPSLongitude) {
    let longitude = parseFloat(exif.GPSLongitude, 10);
    let latitude = parseFloat(exif.GPSLatitude, 10);
    longitude = longitude < 0 ? longitude : -longitude;

    return { latitude, longitude };
  }

  return null;
}

export function getDateFromExif(exif) {
  if (exif?.DateTimeOriginal) {
    const parts = exif.DateTimeOriginal.split(' ');
    const dateString = `${parts[0].replace(/:/g, '-')}T${parts[1]}Z`;

    const date = new Date(dateString);

    // exif date string is in the current timezone of the device
    // we need to adjust it to UTC
    date.setMinutes(date.getMinutes() + date.getTimezoneOffset());

    return date.toISOString();
  }

  return null;
}

export default function PhotoCapture({ isRequired, onChange, uri, style }) {
  const [showLoader, setShowLoader] = React.useState(false);
  const theme = useTheme();
  const commonStyles = useStyles();

  const photoOptions = {
    quality: config.IMAGE_COMPRESSION_QUALITY,
    exif: true,
  };

  const pickImage = async () => {
    const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (status !== 'granted') {
      Alert.alert('Error', `status: ${status}`);
      // 'Media library permissions are required chose a photo.'

      return;
    }

    // For `ImagePicker.launchImageLibraryAsync`: there may be issues with this on android if the memory on the device is low.
    // I'm not sure that there is a great solution for this app since the app reboots and it's
    // not set up to go back to the report screen. I'm going to just leave it as is for now and wait
    // until we have users running into it. I'm guessing that most users will be capturing new photos anyways.
    // Ref: https://github.com/expo/expo/issues/11103
    let result;
    try {
      result = await ImagePicker.launchImageLibraryAsync(photoOptions);
    } catch (error) {
      console.log('error', error);
    }

    if (!result.cancelled) {
      const { uri, exif } = result;

      const coordinates = pointCoordinatesToString(getCoordinatesFromExif(exif));

      onChange({
        uri,
        type: mime.getType(uri),
        name: 'photo',
        coordinates,
        date: getDateFromExif(exif),
      });
    }
  };

  const captureImage = async () => {
    const { status } = await ImagePicker.requestCameraPermissionsAsync();
    if (status !== 'granted') {
      // 'Cameral permissions are required to take a new photo.'
      Alert.alert('Error', `status: ${status}`);

      return;
    }

    let result;
    try {
      result = await ImagePicker.launchCameraAsync(photoOptions);
    } catch (error) {
      console.log('error', error);
    }

    if (!result.cancelled) {
      const { uri, exif } = result;
<commit_msg>fix(front): work-around for camera bug during tracking<commit_after>import { Button, Text, useTheme } from '@ui-kitten/components';
import * as ImagePicker from 'expo-image-picker';
import { unregisterAllTasksAsync } from 'expo-task-manager';
import { reloadAsync } from 'expo-updates';
import mime from 'mime';
import propTypes from 'prop-types';
import React from 'react';
import { Alert, Image, StyleSheet, View } from 'react-native';
import config from '../../services/config';
import { getIcon } from '../../services/icons';
import { ACCURACY, getLocation } from '../../services/location';
import useStyles, { PADDING } from '../../services/styles';
import { pointCoordinatesToString } from '../../services/utilities';
import Spinner from '../Spinner';

const THUMBNAIL_SIZE = 110;
export function getCoordinatesFromExif(exif) {
  if (exif?.GPSLatitude && exif?.GPSLongitude) {
    let longitude = parseFloat(exif.GPSLongitude, 10);
    let latitude = parseFloat(exif.GPSLatitude, 10);
    longitude = longitude < 0 ? longitude : -longitude;

    return { latitude, longitude };
  }

  return null;
}

export function getDateFromExif(exif) {
  if (exif?.DateTimeOriginal) {
    const parts = exif.DateTimeOriginal.split(' ');
    const dateString = `${parts[0].replace(/:/g, '-')}T${parts[1]}Z`;

    const date = new Date(dateString);

    // exif date string is in the current timezone of the device
    // we need to adjust it to UTC
    date.setMinutes(date.getMinutes() + date.getTimezoneOffset());

    return date.toISOString();
  }

  return null;
}

const displayCameraActivityFailedAlert = () => {
  Alert.alert('The app is not able to open your camera.', 'Restarting the app can solve this issue. Restart now?', [
    {
      text: 'Cancel',
    },
    {
      text: 'Ok',
      onPress: async () => {
        await unregisterAllTasksAsync();
        await reloadAsync();
      },
    },
  ]);
};

export default function PhotoCapture({ isRequired, onChange, uri, style }) {
  const [showLoader, setShowLoader] = React.useState(false);
  const theme = useTheme();
  const commonStyles = useStyles();

  const photoOptions = {
    quality: config.IMAGE_COMPRESSION_QUALITY,
    exif: true,
  };

  const pickImage = async () => {
    const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (status !== 'granted') {
      Alert.alert('Error', `status: ${status}`);
      // 'Media library permissions are required chose a photo.'

      return;
    }

    // For `ImagePicker.launchImageLibraryAsync`: there may be issues with this on android if the memory on the device is low.
    // I'm not sure that there is a great solution for this app since the app reboots and it's
    // not set up to go back to the report screen. I'm going to just leave it as is for now and wait
    // until we have users running into it. I'm guessing that most users will be capturing new photos anyways.
    // Ref: https://github.com/expo/expo/issues/11103
    let result;
    try {
      result = await ImagePicker.launchImageLibraryAsync(photoOptions);
    } catch (error) {
      console.log('error', error);
    }

    if (!result.cancelled) {
      const { uri, exif } = result;

      const coordinates = pointCoordinatesToString(getCoordinatesFromExif(exif));

      onChange({
        uri,
        type: mime.getType(uri),
        name: 'photo',
        coordinates,
        date: getDateFromExif(exif),
      });
    }
  };

  const captureImage = async () => {
    const { status } = await ImagePicker.requestCameraPermissionsAsync();
    if (status !== 'granted') {
      // 'Cameral permissions are required to take a new photo.'
      Alert.alert('Error', `status: ${status}`);

      return;
    }

    let result;
    try {
      result = await ImagePicker.launchCameraAsync(photoOptions);
    } catch (error) {
      if (error.message.includes("Call to function 'ExponentImagePicker.launchCameraAsync' has been rejected")) {
        displayCameraActivityFailedAlert();
      } else {
        throw error;
      }
    }

    if (!result.cancelled) {
      const { uri, exif } = result;

{'fraction_non_alphanumeric': 0.12705944378542244, 'fraction_numerical': 0.0039541320680110716, 'mean_word_length': 3.123913043478261, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 9, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3511000', 'n_tokens_mistral': 2286, 'n_tokens_neox': 2211, 'n_words': 682}