<commit_before>/* eslint-disable arrow-body-style */
import React from 'react';
import { StyleSheet } from 'react-native';

import { IconButton } from './IconButton';
import { DownloadIcon } from './icons';
import { BLACK } from '../globalStyles/index';
import { PaperModalContainer } from './PaperModal/PaperModalContainer';
import { PaperInputModal } from './PaperModal/PaperInputModal';
import { useToggle } from '../hooks/useToggle';

const EMAIL_REGEXP = new RegExp(/^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/);

export const ExportTemperatureDataButton = () => {
  const [isOpen, toggleOpen] = useToggle(false);

  return (
    <>
      <IconButton
        onPress={toggleOpen}
        Icon={<DownloadIcon color={BLACK} />}
        containerStyle={localStyles.iconButton}
      />
      <PaperModalContainer isVisible={isOpen} onClose={toggleOpen}>
        <PaperInputModal
          content="A CSV File will be sent to this email address"
          Icon={<DownloadIcon size={40} />}
          buttonText="Download"
          placeholder="Email"
          onButtonPress={toggleOpen}
          validator={input => EMAIL_REGEXP.test(input)}
        />
      </PaperModalContainer>
    </>
  );
};

const localStyles = StyleSheet.create({
  iconButton: {
    flexBasis: 50,
    justifyContent: 'center',
  },
});<commit_msg>Add TemperatureDataButton component to pass in TextInput components<commit_after>/* eslint-disable react/forbid-prop-types */
/* eslint-disable arrow-body-style */
import React, { useRef, useState } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { TextInput, ToastAndroid, StyleSheet } from 'react-native';

import { IconButton } from './IconButton';
import { DownloadIcon } from './icons';
import { PaperModalContainer } from './PaperModal/PaperModalContainer';
import { PaperInputModal } from './PaperModal/PaperInputModal';

import { useToggle } from '../hooks/useToggle';
import { PermissionActions } from '../actions/PermissionActions';
import { emailVaccineReport } from '../utilities/vaccineReport';
import { selectCurrentUser } from '../selectors/user';
import { useLoadingIndicator } from '../hooks/index';
import { BLACK, SUSSOL_ORANGE } from '../globalStyles/index';
import { generalStrings } from '../localization/index';

const toastReportGenerationFailed = () =>
  ToastAndroid.show(generalStrings.report_generation_failed, ToastAndroid.LONG);
const toastNoData = () => ToastAndroid.show(generalStrings.no_data_for_sensor, ToastAndroid.LONG);
const toastNoPermission = () =>
  ToastAndroid.show(generalStrings.require_permission_to_send_data, ToastAndroid.LONG);

export const ExportTemperatureDataButtonComponent = ({
  sensor,
  requestStorageWritePermission,
  currentUser,
}) => {
  const [isOpen, toggle] = useToggle(false);
  const [email, setEmail] = useState('');
  const [comment, setComment] = useState('');
  const withLoadingIndicator = useLoadingIndicator();
  const emailRef = useRef(null);
  const commentRef = useRef(null);

  const reset = () => {
    toggle();
    setEmail('');
    setComment('');
  };

  const tryDownload = () =>
    // Request storage permission is a thunk which returns true/false if permission was granted.
    // If permission has already been granted, true is returned.
    requestStorageWritePermission()
      // After checking for storage write permission, cache the current email/comment and clear
      // the current state - primarily to close the modal, making room for the full-screen spinner.
      // or so the modal is closed and a toast will provide feedback.
      .then(success => {
        const cached = { email, comment, success };
        if (!success) toastNoPermission();
        reset();
        return cached;
      })
      // Once permission has been ensured and the dialog is closed, block with a full screen spinner
      // while generating the report - it could be large.
      .then(({ success, emailValue, commentValue }) => {
        if (success) {
          withLoadingIndicator(() =>
            emailVaccineReport(sensor, currentUser, emailValue, commentValue)
          );
        }
      })
      .catch(() => toastReportGenerationFailed());

  return (
    <>
      <IconButton
        onPress={() => {
          if (sensor.logs?.length > 0) toggle();
          else toastNoData();
        }}
        Icon={<DownloadIcon color={BLACK} />}
        containerStyle={localStyles.iconButton}
      />
      <PaperModalContainer isVisible={isOpen} onClose={reset}>
        <PaperInputModal
          content={generalStrings.a_csv_file}
          Icon={<DownloadIcon size={40} />}
          buttonText={generalStrings.download}
          placeholder={generalStrings.email}
          onButtonPress={tryDownload}
        >
          <TextInput
            selectTextOnFocus
            ref={emailRef}
            placeholder={generalStrings.email}
            underlineColorAndroid={SUSSOL_ORANGE}
            value={email}
            style={localStyles.textInput}
            onChangeText={setEmail}
            blurOnSubmit={false}
            onSubmitEditing={() => commentRef?.current?.focus()}
          />
          <TextInput
            selectTextOnFocus
            ref={commentRef}
            placeholder={generalStrings.comment}
            underlineColorAndroid={SUSSOL_ORANGE}
            value={comment}
            style={localStyles.textInput}
            onChangeText={setComment}
            blurOnSubmit={false}
            onSubmitEditing={() => emailRef?.current?.focus()}
          />
        </PaperInputModal>
      </PaperModalContainer>
    </>
  );
};

const localStyles = StyleSheet.create({
  iconButton: {
    flexBasis: 50,
    justifyContent: 'center',
  },
  button: {
    height: 50,
    backgroundColor: SUSSOL_ORANGE,
    width: '100%',
  },
  textInput: {
    color: SUSSOL_ORANGE,
    height: 50,
    fontSize: 14,
    fontWeight: '400',
    width: '100%',
    maxHeight: 50,
  },
});

ExportTemperatureDataButtonComponent.propTypes = {
  sensor: PropTypes.object.isRequired,
  requestStorageWritePermission: PropTypes.func.isRequired,
  currentUser: PropTypes.object.isRequired,
};

const stateToProps = state => {
  const currentUser = selectCurrentUser(state);
  return { currentUser };
};

const dispatchToProps = dispatch => {
  const requestStorageWritePermission = () => dispatch(PermissionActions.requestWriteStorage());
  return { requestStorageWritePermission };
};

export const ExportTemperatureDataButton = connect(
  stateToProps,
  dispatchToProps
)(ExportTemperatureDataButtonComponent);
{'fraction_non_alphanumeric': 0.12329390354868063, 'fraction_numerical': 0.004246284501061571, 'mean_word_length': 3.134796238244514, 'pattern_counts': {'":': 0, '<': 22, '<?xml version=': 0, '>': 41, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '121836', 'n_tokens_mistral': 1817, 'n_tokens_neox': 1786, 'n_words': 419}