import React, { useState, useEffect } from "react"; import { StyleSheet, SafeAreaView, Text, TextInput, View, ScrollView, FlatList } from "react-native"; import { Button} from 'native-base'; import { useTheme } from '@react-navigation/native'; import Icon from 'react-native-vector-icons/MaterialCommunityIcons'; import {SearchBar} from 'react-native-elements'; import { TouchableOpacity } from "react-native-gesture-handler"; function Nutrition({navigation, route}) { const { colors } = useTheme(); const [mealName, setMealName] = useState(''); const [newDate, setNewDate] = useState(''); const [calories, setCalories] = useState(''); const [carbohydrates, setCarbohydrates] = useState(''); const [proteins, setProteins] = useState(''); const [fats, setFats] = useState(''); const [itemSearched, setItemSearched] = useState(''); const [macros, setMacros] = useState(''); const [myMeals, setMyMeals] = useState([]); const [userGender, setUserGender] = useState(''); const [userHeight, setUserHeight] = useState(''); const [userAge, setUserAge] = useState(''); const [userWeight, setUserWeight] = useState(''); const [allMeals, setAllMeals] = useState([]); const [searchedMacros, setSearchedMacros] = useState([]); const [user, setUser] = useState(route.params.username) const [reccommendCalories, setReccommendCalories] = useState(); [todayCalories, setTodayCalories] = useState(); const [todayCarbs, setTodayCarbs] = useState(); const [todayFats, setTodayFats] = useState(); const [todayProteins, setTodayProteins] = useState(); const [givenDate, setGivenDate] = useState(); var dateDesired = new Date().setHours(0, 0, 0, 0); const ALLDATA = [ { id: 0, name: 'Apple: 30 cal' }, { id: 1, name: 'Cupcake: 250 cal' }, { id: 2, name: 'Pizza: 300 cal' }, ] const FILTERDATA = [ { id: 0, name: 'Apple: 30 cal' }, { id: 1, name: 'Cupcake: 250 cal' }, { id: 2, name: 'Pizza: 300 cal' }, ] useEffect(() => { getMyNutritionDB(user, dateDesired); getUser(); setMacros(ALLDATA) setSearchedMacros(FILTERDATA) }, []); //Function to get nutrition database info. async function getMyNutritionDB(name, date){ await fetch(localhost+'/nutritionDB/'+user+'/'+date, { method: "GET", headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate' } }) .then(function(response) { if (response.status === 200 || response.status === 201) { // Successful GET // Set Fields to correct values response.json().then(function(data) { setMyMeals(data.map(item => ({ userMealName : item.MealName, userMealCalories: item.calories, userCarbs : item.carbohydrates, userProteins : item.protein, userFats : item.fats, userMealDate : item.date })) ) }); //getDaily(); } else { console.log('issue getMyMeal. Status Code: ' + response.status); } }) .catch(function(err) { console.log('Fetch Error :-S', err); }); getDaily(); } //Function to get user information for required calorie reccommendation. async function getUser(){ await fetch(localhost+'/userprofile/user/'+user, { method: "GET", headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate' } }) .then(function(response) { if (response.status === 200 || response.status === 201) { // Successful GET // Set Fields to correct values response.json().then(function(data) { if (data[0].gender.toLowerCase() == "female") { setReccommendCalories((655 + (4.35 * userWeight) + (4.7 * userHeight) - (4.7 * userAge))); } else { setReccommendCalories((66 + (6.2 * data[0].weight) + (12.7 * data[0].height) - (6.76 * data[0].age))); } }); } else { console.log('issue getUser. Status Code: ' + response.status); } }) .catch(function(err) { console.log('Fetch Error :-S', err); }); } //Function that handles searching for items. function handleSearch(searchText) { setItemSearched(searchText) if (searchText === "") { setSearchedMacros(macros) } if (searchText) { const searchData = macros.filter(function (macro) { const items = macro ? macro.name.toUpperCase() : ''.toUpperCase(); const searchItem = searchText.toUpperCase(); return items.indexOf(searchItem) > -1; }) setSearchedMacros(searchData) } } //Function for posting new meals. function postNutritionDB(){ fetch(localhost+'/nutritionDB', { method: "POST", headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ "owner": user, "date": new Date().setHours(0,0,0,0), "MealName": mealName, "calories" : calories, "carbohydrates" : carbohydrates, "protein" : proteins, "fats" : fats }) }) .then( function(response) { if (response.status === 200 || response.status === 201) { // Successful POST console.log('good nutritionDB'); alert("Successfully added data!") } else { // Examine the text in the response console.log('issue in nutritionDB. Status code: '+ response.status); alert("Unsuccessful posted meal") } } ) .catch(function(err) { console.log('Fetch Error :-S', err); }); } function handleSubmit(){ console.log(calories) console.log(mealName) console.log(user) postNutritionDB(); } function renderSeparator() { return ( <View style={{ borderBottomColor: '#c4baba', borderBottomWidth: 1, }} /> ); } function renderMacros(macroItem){ return( <Text style={ [styles.mealName, {color: colors.text}] }>{macroItem.item.name}</Text> ); } //Function for deleting meals from database. function delMeal(name){ fetch(localhost+'/nutritionDB/' + name, { method: "DELETE", headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate' } }) .then( function(response) { if (response.status === 200 || response.status === 201) { // Successful POST response.json().then(function(data) { console.log(data); }) } else { // Examine the text in the response console.log('issue in delMeal. Status code: '+ response.status); } } ) .catch(function(err) { console.log('Fetch Error :-S', err); }); } //Function to ensure that calorie count is correct. function getDaily() { console.log("Getting info"); let tempCarbs = 0, tempProtein = 0, tempCalories = 0, tempFats = 0; for (var entry of myMeals.entries()) { tempCarbs += entry[1].userCarbs; tempProtein += entry[1].userProteins; tempCalories += entry[1].userMealCalories; tempFats += entry[1].userFats; } setTodayCalories(tempCalories); setTodayFats(tempFats); setTodayCarbs(tempCarbs); setTodayProteins(tempProtein); } function handleNewDate() { var date = new Date(givenDate); getMyNutritionDB(user, date.setHours(0,0,0,0)); } return ( <ScrollView> <SafeAreaView style={ [styles.screen, {flexDirection:"column"}] }> <Text style={ [styles.title, {color: colors.text}] }>Nutrition:</Text> <Text style={ [styles.subsection, {color: colors.text}] }>Past Meals:</Text> <View> {myMeals.map(key=> { return <View style={{flexDirection: "column"}}> <Text style={ [styles.mealName, {color: colors.text}] }>{key.userMealName}</Text> <Text style={ [styles.mealName, {color: colors.text}] }>{key.userMealCalories}</Text> <Icon name='delete' color="#5c5a55" size={20} onPress={()=>delMeal(key.userMealName)}/> </View> })} </View> <Text style={ [styles.mealName, {color: colors.text}] }>{"Daily National Standard Calories: 2000\nReccommeneded Calories: " + reccommendCalories}</Text> <Text style={ [styles.mealName, {color: colors.text}] }>{"Your calories: " + todayCalories}</Text> <Text style={ [styles.mealName, {color: colors.text}] }>{"Your carbohydrates(grams): " + todayCarbs}</Text> <Text style={ [styles.mealName, {color: colors.text}] }>{"Your fats(grams): " + todayFats}</Text> <Text style={ [styles.mealName, {color: colors.text}] }>{"Your proteins(grams): " + todayProteins}</Text> <Text style={ [styles.subsection, {color: colors.text}] }>Change Date (mm/dd/yyyy):</Text> <TextInput style={ [styles.input, {color: colors.text}] } onChangeText={(date) => setGivenDate(date)} /> <View style={{flexDirection: "row"}}> <Button style={ styles.nextDate } onPress={handleNewDate}> <Text style={ styles.nextText } >Submit</Text> </Button> </View> <Text style={ [styles.subsection, {color: colors.text}] }>Record Meal:</Text> <Text style={ [styles.subtitle, {color: colors.text}] }>Meal Name:</Text> <TextInput style={ [styles.input, {color: colors.text}] } onChangeText={(mealName) => setMealName(mealName)} /> <Text style={ [styles.subtitle, {color: colors.text}] }>Calories:</Text> <TextInput style={ [styles.input, {color: colors.text}] } onChangeText={(calories) => setCalories(calories)} /> <Text style={ [styles.subtitle, {color: colors.text}] }>Carbohydrates:</Text> <TextInput style={ [styles.input, {color: colors.text}] } onChangeText={(carbohydrates) => setCarbohydrates(carbohydrates)} /> <Text style={ [styles.subtitle, {color: colors.text}] }>Proteins:</Text> <TextInput style={ [styles.input, {color: colors.text}] } onChangeText={(proteins) => setProteins(proteins)} /> <Text style={ [styles.subtitle, {color: colors.text}] }>Fats:</Text> <TextInput style={ [styles.input, {color: colors.text}] } onChangeText={(fats) => setFats(fats)} /> <View style={{flexDirection: "row"}}> <Button style={ styles.nextButton } onPress={handleSubmit}> <Text style={ styles.nextText } >Submit</Text> </Button> </View> <View style={{ borderBottomColor: '#c4baba', borderBottomWidth: 1, }} /> <Text style={ [styles.subsection, {color: colors.text}] }>Search for Macros:</Text> <SearchBar round lightTheme="true" containerStyle={{backgroundColor: colors.background, borderTopColor: "transparent", borderBottomColor: "transparent"}} placeholder="Look up an item here" value={itemSearched} onChangeText={(searchText) => handleSearch(searchText)} onClear={(searchText) => handleSearch('')} /> <FlatList data={searchedMacros} ItemSeparatorComponent={renderSeparator} renderItem={(macroItem) => renderMacros(macroItem)} /> </SafeAreaView> </ScrollView> ); } const styles = StyleSheet.create({ screen:{ marginTop: "20%", paddingLeft: "5%", paddingRight: "5%", paddingBottom: "10%", marginLeft: "10%", marginRight: "10%" }, title: { fontSize: 25, fontWeight: "bold", marginTop: "10%", paddingBottom: "5%", textAlign:"center" }, subsection: { fontSize: 20, fontWeight: "bold", textAlign:"center" }, subtitle: { fontSize: 16, textAlign:"left", fontWeight: "bold", color: '#5c5a55' }, mealName: { fontSize: 16, textAlign:"left", fontWeight: "bold", color: '#5c5a55', //marginTop: '10%', //marginBottom: '10%' }, input: { width: "100%", height: 40, borderBottomWidth: 1 }, nextButton: { width: '100%', justifyContent: 'center', backgroundColor: "#d4911c", borderRadius: 10, alignItems: "center", marginBottom: 10, marginTop: 50 }, nextText: { fontSize: 16, fontWeight: "bold", color: "white" }, nextDate: { width: '25%', justifyContent: 'center', backgroundColor: "#d4911c", borderRadius: 10, alignItems: "center", }, }); export default Nutrition;