Massive/EditSet.tsx

235 lines
6.9 KiB
TypeScript
Raw Normal View History

import AsyncStorage from '@react-native-async-storage/async-storage';
2022-07-11 00:28:30 +00:00
import {
RouteProp,
useFocusEffect,
useNavigation,
useRoute,
} from '@react-navigation/native';
2022-07-20 03:22:56 +00:00
import React, {
useCallback,
useContext,
useEffect,
useRef,
useState,
} from 'react';
2022-07-11 00:28:30 +00:00
import {NativeModules, ScrollView, StyleSheet, View} from 'react-native';
2022-07-09 04:38:57 +00:00
import DateTimePickerModal from 'react-native-modal-datetime-picker';
2022-07-11 00:28:30 +00:00
import {Button, IconButton, TextInput} from 'react-native-paper';
import {DatabaseContext} from './App';
2022-07-11 00:28:30 +00:00
import {HomePageParams} from './HomePage';
import {Plan} from './plan';
import Set from './set';
import {DAYS, format} from './time';
2022-07-03 01:50:01 +00:00
export default function EditSet() {
2022-07-11 00:28:30 +00:00
const {params} = useRoute<RouteProp<HomePageParams, 'EditSet'>>();
const [name, setName] = useState(params.set.name);
const [reps, setReps] = useState(params.set.reps.toString());
const [weight, setWeight] = useState(params.set.weight.toString());
const [created, setCreated] = useState(new Date(params.set.created));
const [unit, setUnit] = useState(params.set.unit);
2022-07-10 04:22:19 +00:00
const [showDate, setShowDate] = useState(false);
2022-07-20 03:22:56 +00:00
const weightRef = useRef<any>(null);
const db = useContext(DatabaseContext);
const navigation = useNavigation();
2022-07-11 00:28:30 +00:00
useFocusEffect(
useCallback(() => {
navigation.getParent()?.setOptions({
headerLeft: () => (
<IconButton icon="arrow-back" onPress={() => navigation.goBack()} />
),
title: 'Set',
});
2022-07-11 00:32:13 +00:00
}, [navigation]),
2022-07-11 00:28:30 +00:00
);
const getTodaysPlan = useCallback(async (): Promise<Plan[]> => {
const today = DAYS[new Date().getDay()];
const [result] = await db.executeSql(
`SELECT * FROM plans WHERE days LIKE ? LIMIT 1`,
[`%${today}%`],
);
return result.rows.raw();
}, [db]);
const getTodaysSets = useCallback(async (): Promise<Set[]> => {
const today = new Date().toISOString().split('T')[0];
const [result] = await db.executeSql(
`SELECT * FROM sets WHERE created LIKE ? ORDER BY created DESC`,
[`${today}%`],
);
return result.rows.raw();
}, [db]);
2022-07-19 02:26:00 +00:00
const getBest = useCallback(
async (query: string): Promise<Set> => {
const bestWeight = `
SELECT name, reps, unit, MAX(weight) AS weight
FROM sets
WHERE name = ?
GROUP BY name;
`;
const bestReps = `
SELECT name, MAX(reps) as reps, unit, weight
FROM sets
WHERE name = ?
AND weight = ?
GROUP BY name;
`;
const [weightResult] = await db.executeSql(bestWeight, [query]);
if (!weightResult.rows.length)
2022-07-19 02:26:00 +00:00
return {
weight: 0,
name: '',
reps: 0,
created: new Date().toISOString(),
id: 0,
};
const [repsResult] = await db.executeSql(bestReps, [
query,
weightResult.rows.item(0).weight,
]);
return repsResult.rows.item(0);
},
[db],
);
const predict = useCallback(async () => {
if ((await AsyncStorage.getItem('predictiveSets')) === 'false') return;
const todaysPlan = await getTodaysPlan();
if (todaysPlan.length === 0) return;
const todaysSets = await getTodaysSets();
const todaysWorkouts = todaysPlan[0].workouts.split(',');
2022-07-19 02:26:00 +00:00
let nextWorkout = todaysWorkouts[0];
if (todaysSets.length > 0) {
const count = todaysSets.filter(
set => set.name === todaysSets[0].name,
).length;
const maxSets = await AsyncStorage.getItem('maxSets');
nextWorkout = todaysSets[0].name;
if (count >= Number(maxSets))
nextWorkout =
todaysWorkouts[todaysWorkouts.indexOf(todaysSets[0].name!) + 1];
}
2022-07-19 02:26:00 +00:00
const best = await getBest(nextWorkout);
setName(best.name);
setReps(best.reps.toString());
setWeight(best.weight.toString());
setUnit(best.unit);
}, [getTodaysSets, getTodaysPlan, getBest]);
useEffect(() => {
if (params.set.id) return;
predict();
2022-07-10 12:06:48 +00:00
}, [predict, params.set.id]);
2022-07-09 04:38:57 +00:00
2022-07-10 12:06:48 +00:00
const onConfirm = (date: Date) => {
setCreated(date);
2022-07-10 04:22:19 +00:00
setShowDate(false);
2022-07-09 04:38:57 +00:00
};
const update = useCallback(async () => {
console.log(`${EditSet.name}.update`, params.set);
await db.executeSql(
`UPDATE sets SET name = ?, reps = ?, weight = ?, created = ?, unit = ? WHERE id = ?`,
[name, reps, weight, created.toISOString(), unit, params.set.id],
);
navigation.goBack();
2022-07-10 12:06:48 +00:00
}, [params.set, name, reps, weight, created, unit, db, navigation]);
const notify = useCallback(async () => {
const enabled = await AsyncStorage.getItem('alarmEnabled');
if (enabled !== 'true') return;
const minutes = await AsyncStorage.getItem('minutes');
const seconds = await AsyncStorage.getItem('seconds');
const milliseconds = Number(minutes) * 60 * 1000 + Number(seconds) * 1000;
NativeModules.AlarmModule.timer(milliseconds);
}, []);
const add = useCallback(async () => {
if (name === undefined || reps === '' || weight === '') return;
const insert = `
INSERT INTO sets(name, reps, weight, created, unit)
VALUES (?,?,?,?,?)
`;
await db.executeSql(insert, [
name,
reps,
weight,
created.toISOString(),
unit || 'kg',
]);
notify();
navigation.goBack();
2022-07-10 12:06:48 +00:00
}, [name, reps, weight, created, unit, db, navigation, notify]);
const save = useCallback(async () => {
if (params.set.id) return update();
return add();
2022-07-10 12:06:48 +00:00
}, [update, add, params.set.id]);
2022-07-03 01:50:01 +00:00
return (
2022-07-11 00:28:30 +00:00
<View style={{padding: 10}}>
<ScrollView style={{height: '90%'}}>
<TextInput
style={styles.marginBottom}
2022-07-20 03:22:56 +00:00
label="Name"
2022-07-11 00:28:30 +00:00
value={name}
onChangeText={setName}
autoCorrect={false}
/>
<TextInput
style={styles.marginBottom}
2022-07-20 03:22:56 +00:00
label="Reps"
2022-07-11 00:28:30 +00:00
keyboardType="numeric"
value={reps}
onChangeText={setReps}
2022-07-20 03:22:56 +00:00
autoFocus
blurOnSubmit={false}
onSubmitEditing={() => weightRef.current?.focus()}
2022-07-11 00:28:30 +00:00
/>
<TextInput
style={styles.marginBottom}
2022-07-20 03:22:56 +00:00
label="Weight"
2022-07-11 00:28:30 +00:00
keyboardType="numeric"
value={weight}
onChangeText={setWeight}
onSubmitEditing={save}
2022-07-20 03:22:56 +00:00
ref={weightRef}
2022-07-11 00:28:30 +00:00
/>
<TextInput
style={styles.marginBottom}
label="Unit (kg)"
value={unit}
onChangeText={setUnit}
onSubmitEditing={save}
/>
2022-07-11 00:28:30 +00:00
<Button
style={styles.marginBottom}
icon="calendar-outline"
onPress={() => setShowDate(true)}>
{format(created)}
</Button>
<DateTimePickerModal
isVisible={showDate}
mode="datetime"
onConfirm={onConfirm}
onCancel={() => setShowDate(false)}
date={created}
/>
</ScrollView>
<Button mode="contained" icon="save" onPress={save}>
Save
</Button>
2022-07-11 00:28:30 +00:00
</View>
2022-07-03 01:50:01 +00:00
);
}
const styles = StyleSheet.create({
marginBottom: {
2022-07-04 04:03:48 +00:00
marginBottom: 10,
},
2022-07-03 01:50:01 +00:00
});