import React, {
useRef,
useCallback,
useContext,
useEffect,
useState,
} from 'react';
import {
View,
Text,
Button,
StyleSheet,
Alert,
Linking,
ActivityIndicator,
} from 'react-native';
import Map from '../component/Map';
import Search from '../component/Search';
import {MapContext} from './../context/MapContext';
import {useCameraDevices, Camera} from 'react-native-vision-camera';
import RNFS from 'react-native-fs';
import {url} from '../url';
// import Icon from 'react-native-vector-icons/FontAwesome5';
import {BLACK, GRAY, PRIMARY} from '../color';
export default function Main({navigation}) {
const {onQuery, searchQuery, location, nodes} = useContext(MapContext);
const [isDrivingStarted, setIsDrivingStarted] = useState(false);
const [shouldLog, setShouldLog] = useState(false);
const [infoMessage, setInfoMessage] = useState('');
const [sendTime, setSendTime] = useState(null);
const [devicesLoaded, setDevicesLoaded] = useState(false);
const devices = useCameraDevices();
const device = devices.back;
const camera = useRef(null);
let timerId;
const requestCameraPermission = useCallback(async () => {
const permission = await Camera.requestCameraPermission();
if (permission === 'denied') await Linking.openSettings();
}, []);
useEffect(() => {
requestCameraPermission();
if (
devices &&
devices.back &&
devices.back.devices.includes('telephoto-camera') &&
!devicesLoaded
) {
const telephotoCamera = devices.back.devices.find(
device => device === 'telephoto-camera',
);
if (telephotoCamera) {
camera.current = telephotoCamera;
setDevicesLoaded(true);
}
}
}, [devices, devicesLoaded]);
useEffect(() => {
if (devicesLoaded && shouldLog) {
const intervalId = setInterval(() => {
setInfoMessage('정보가 송신되었습니다.');
setSendTime(new Date());
takePicture();
}, 5000);
return () => {
clearInterval(intervalId);
setInfoMessage('');
setSendTime(null);
};
}
}, [devicesLoaded, shouldLog]);
const handleStartDriving = () => {
setIsDrivingStarted(prevState => !prevState);
if (isDrivingStarted) {
setShouldLog(false);
clearInterval(timerId);
} else {
setShouldLog(true);
}
};
const takePicture = async () => {
if (!devicesLoaded || !camera.current) {
console.log('Devices are not loaded or camera is not available.');
return;
}
const photoResult = await camera.current.takePhoto({
flash: 'off',
qualityPrioritization: 'speed',
});
if (photoResult && photoResult.path) {
const {path} = photoResult;
let pathSplit = path.split('/');
let fileName = pathSplit[pathSplit.length - 1];
let splitFileName = fileName.split('.');
let sFileName = splitFileName[0];
let files = [
{
name: 'file',
filename: fileName,
filepath: path,
filetype: 'image/jpg',
},
];
let upload = response => {
let jobId = response.jobId;
console.log('UPLOAD HAS BEGUN! JobId: ' + jobId);
};
let uploadProgress = response => {
let percentage = Math.floor(
(response.totalBytesSent / response.totalBytesExpectedToSend) * 100,
);
console.log('UPLOAD IS ' + percentage + '% DONE!');
};
await RNFS.uploadFiles({
toUrl: `${url}/action/image_summit`,
files: files,
method: 'POST',
headers: {},
begin: upload,
progress: uploadProgress,
})
.promise.then(response => {
if (response.statusCode !== 200) {
throw new Error('SERVER ERROR: ' + response.statusCode);
}
return fetch(`${url}/action/image_anal`, {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: JSON.stringify({
filename: sFileName,
file_type: '.jpg',
gps_x: location.latitude,
gps_y: location.longitude,
}),
});
})
.then(response => response.json())
.then(data => {
const {node, rain} = data;
if (node === null || rain !== 'rain') {
throw new Error('No data or not fog');
}
Alert.alert(
'폭우 발생 알람',
'전방에 폭우가 발생하였습니다. 감속하십시오',
);
})
.catch(error => {
console.error('Error during file upload or image analysis:', error);
});
} else {
console.log('Failed to take a photo.');
}
};
//처음 검색에만 실행 됨 검색마다 실행되어야함
if (!location || (searchQuery && !nodes.length)) {
return (
경로를 탐색 중입니다.
);
}
return (
{/* navigation.openDrawer()}
/> */}
{/*
{devicesLoaded && shouldLog && (
)}
{infoMessage && sendTime && (
{infoMessage}
Sent at: {sendTime.toLocaleTimeString()}
{infoMessage === '정보가 송신되었습니다.'
? '사진을 촬영합니다.'
: ''}
)}
*/}
);
}
const styles = StyleSheet.create({
container: {
margin: 16,
justifyContent: 'center',
alignItems: 'center',
},
containerTop: {
position: 'absolute',
top: 20,
zIndex: 1,
flexDirection: 'row',
width: '100%',
justifyContent: 'space-between',
alignItems: 'center',
paddingHorizontal: 7,
},
infoContainer: {
marginTop: 16,
justifyContent: 'center',
alignItems: 'center',
},
normalText: {
color: BLACK,
},
});