import React, { useState, useEffect, useRef } from "react"; import PropTypes from "prop-types"; import { Box, Button, Heading, Text } from "grommet"; import { Aid, Impact } from "grommet-icons"; import Telegram from "../utils/telegram"; import { TG_API, TG_USERID } from "../config"; function sendNotification(close) { if (window.sendingAccidentAlert) return; window.sendingAccidentAlert = true; const bot = new Telegram(TG_API); bot.sendMessage(TG_USERID, "User detected in an accident. Location has been attached below."); navigator.geolocation.getCurrentPosition( position => { window.sendingAccidentAlert = false; bot.sendLocation( TG_USERID, position.coords.latitude, position.coords.longitude); }, () => { window.sendingAccidentAlert = false; bot.sendMessage(TG_USERID, "Error retrieving location"); } ); setTimeout(close, 2000); } function Accident(props) { const threshold = 20; const [ time, setTime ] = useState(threshold); const countRef = useRef(null); function decrementTime(time) { if (time === 0) { clearInterval(countRef.current); sendNotification(props.close); return 0; } return time - 1; } useEffect(() => { countRef.current = setInterval(() => setTime(decrementTime), 1000); return () => clearInterval(countRef.current); }, []); function dismiss() { clearTimeout(countRef.current); props.close(); } return ( { time === 0 ? : } { time === 0 ? "Calling Ambulance!" :"Accident Detected!" } { time === 0 ? "Calling Ambulance": `To cancel calling the ambulance, press the button below. (${time})` }