cofounderella/lib/pages/user_data_page.dart

570 lines
19 KiB
Dart
Raw Normal View History

2024-05-05 01:02:09 +02:00
import 'dart:convert';
import 'package:cloud_firestore/cloud_firestore.dart';
2024-05-17 23:08:26 +02:00
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart';
import '../components/location_dialog.dart';
2024-05-10 21:25:25 +02:00
import '../components/my_button.dart';
2024-05-17 23:08:26 +02:00
import '../components/my_drawer.dart';
2024-05-10 21:25:25 +02:00
import '../constants.dart';
2024-05-17 23:08:26 +02:00
import '../enumerations.dart';
import '../forms/skills_form.dart';
2024-05-10 21:25:25 +02:00
import '../models/language.dart';
import '../models/language_setting.dart';
import '../models/location.dart';
2024-05-17 23:08:26 +02:00
import '../services/auth/auth_service.dart';
2024-05-05 01:02:09 +02:00
class UserDataPage extends StatefulWidget {
2024-05-17 23:08:26 +02:00
final bool isRegProcess;
const UserDataPage({super.key, required this.isRegProcess});
2024-05-05 01:02:09 +02:00
@override
State<UserDataPage> createState() => _UserDataPageState();
}
class _UserDataPageState extends State<UserDataPage> {
2024-05-10 21:25:25 +02:00
MyLocation? _mainLocation;
2024-05-10 00:21:23 +02:00
MyLocation? _secondaryLocation;
2024-05-05 01:02:09 +02:00
List<LanguageSetting> languagesList = [];
final List<Language> _selectedLanguages = [];
// get instance of firestore and auth
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
final AuthService _authService = AuthService();
2024-05-08 00:59:16 +02:00
int? _selectedYear;
int? _yearFromDb;
2024-05-06 15:21:21 +02:00
Gender genderView = Gender.none;
int _genderFromDb = 0;
List<Language> _languagesFromDb = [];
2024-05-10 21:25:25 +02:00
MyLocation? _mainLocationFromDb;
MyLocation? _secondaryLocationFromDb;
bool _secondLocationExists = false;
2024-05-06 15:21:21 +02:00
2024-05-05 01:02:09 +02:00
@override
void initState() {
super.initState();
2024-05-06 15:21:21 +02:00
// load settings from database
_fetchSettings();
2024-05-05 01:02:09 +02:00
}
2024-05-06 15:21:21 +02:00
Future<void> _fetchSettings() async {
try {
// Fetch user ID
String currentUserId = _authService.getCurrentUser()!.uid;
2024-05-05 01:02:09 +02:00
2024-05-06 15:21:21 +02:00
// Fetch user document fields (email, uid, gender, ...) from database
DocumentSnapshot userSnapshot = await _firestore
.collection(Constants.dbCollectionUsers)
2024-05-08 00:59:16 +02:00
.doc(currentUserId)
2024-05-06 15:21:21 +02:00
.get();
2024-05-05 01:02:09 +02:00
2024-05-16 16:57:17 +02:00
if (!userSnapshot.exists || userSnapshot.data() == null) {
return; // should not happen, user entry should exist
}
Map<String, dynamic> userFields =
userSnapshot.data() as Map<String, dynamic>;
2024-05-08 00:59:16 +02:00
// Extract gender and birth year
2024-05-16 16:57:17 +02:00
if (userFields.containsKey(Constants.dbFieldUsersGender)) {
_genderFromDb = userSnapshot[Constants.dbFieldUsersGender];
}
if (userFields.containsKey(Constants.dbFieldUsersYearBorn)) {
_yearFromDb = userSnapshot[Constants.dbFieldUsersYearBorn];
}
2024-05-05 01:02:09 +02:00
2024-05-10 21:25:25 +02:00
// Fetch locations
QuerySnapshot locationSnapshot = await _firestore
.collection(Constants.dbCollectionUsers)
.doc(currentUserId)
.collection(Constants.dbCollectionLocations)
.get();
MyLocation userLoc;
for (var doc in locationSnapshot.docs) {
userLoc = MyLocation(
street: doc['street'],
country: doc['country'],
administrativeArea: doc['administrativeArea'],
locality: doc['locality'],
subLocality: doc['subLocality'],
postalCode: doc['postalCode'],
latitude: doc['latitude'],
longitude: doc['longitude'],
);
if (doc.id == Constants.dbDocMainLocation) {
_mainLocationFromDb = userLoc;
} else if (doc.id == Constants.dbDocSecondLocation) {
_secondaryLocationFromDb = userLoc;
_secondLocationExists = true;
}
}
2024-05-06 15:21:21 +02:00
// Fetch languages
QuerySnapshot languagesSnapshot = await _firestore
.collection(Constants.dbCollectionUsers)
.doc(currentUserId)
.collection(Constants.dbCollectionLanguages)
.get();
2024-05-05 01:02:09 +02:00
2024-05-06 15:21:21 +02:00
List<Language> userLanguages = [];
for (var doc in languagesSnapshot.docs) {
//languages.add(Language.fromDocument(doc));
userLanguages.add(Language(
code: doc.id, // aka doc['code'],
name: doc['name'],
nativeName: doc['nativeName'],
iconFile: doc['iconFile'],
));
2024-05-05 01:02:09 +02:00
}
2024-05-06 15:21:21 +02:00
setState(() {
2024-05-08 00:59:16 +02:00
genderView = Gender.values[_genderFromDb];
_selectedYear = _yearFromDb;
2024-05-06 15:21:21 +02:00
_languagesFromDb = userLanguages;
2024-05-10 21:25:25 +02:00
_mainLocation = _mainLocationFromDb;
_secondaryLocation = _secondaryLocationFromDb;
2024-05-06 15:21:21 +02:00
});
// Load data from JSON file when the widget initializes
loadLanguagesFromJson();
} catch (error) {
2024-05-17 23:08:26 +02:00
_showSnackBar("Error fetching settings: $error");
2024-05-05 01:02:09 +02:00
}
}
2024-05-06 15:21:21 +02:00
/// Loads the languages to display
2024-05-05 01:02:09 +02:00
Future<void> loadLanguagesFromJson() async {
// Load JSON data from assets
2024-05-06 15:21:21 +02:00
String jsonData = await rootBundle.loadString(Constants.pathLanguagesJson);
2024-05-05 01:02:09 +02:00
// Parse JSON into a list of objects
List<dynamic> jsonList = await json.decode(jsonData);
// Create LanguageSetting objects from JSON data
languagesList = jsonList.map((item) {
Language language = Language(
code: item['code'],
name: item['name'],
nativeName: item['nativeName'],
iconFile: item['iconFile'],
);
2024-05-06 15:21:21 +02:00
return LanguageSetting(
language: language,
isSelected: _languagesFromDb.any(
(language) => language.code == item['code'],
),
);
2024-05-05 01:02:09 +02:00
}).toList();
// Update the UI after loading data
setState(() {
2024-05-06 15:21:21 +02:00
if (_selectedLanguages.isEmpty) {
_selectedLanguages.addAll(_languagesFromDb);
}
});
}
2024-05-17 23:08:26 +02:00
Future<bool> saveUserData(BuildContext context) async {
try {
// Get userID from auth service
String currentUserID = _authService.getCurrentUser()!.uid;
// Get references to the current users Firebase collections
DocumentReference userRef =
_firestore.collection(Constants.dbCollectionUsers).doc(currentUserID);
CollectionReference languagesRef =
userRef.collection(Constants.dbCollectionLanguages);
CollectionReference locationsRef =
userRef.collection(Constants.dbCollectionLocations);
if (_selectedYear != _yearFromDb) {
await userRef.update(
{'born': _selectedYear},
);
// update local value
_yearFromDb = _selectedYear;
}
2024-05-08 00:59:16 +02:00
2024-05-17 23:08:26 +02:00
// Update Gender in database - only if value has changed
if (_genderFromDb != genderView.index) {
await userRef.update(
{'gender': genderView.index},
);
// update local value
_genderFromDb = genderView.index;
}
2024-05-06 15:21:21 +02:00
2024-05-17 23:08:26 +02:00
// Save locations
if (_mainLocation != _mainLocationFromDb) {
if (_mainLocation != null) {
// Update existing user document with new locations
await locationsRef
.doc(Constants.dbDocMainLocation)
.set(_mainLocation!.toMap());
}
2024-05-10 21:25:25 +02:00
}
2024-05-17 23:08:26 +02:00
if (_secondaryLocation != _secondaryLocationFromDb) {
if (_secondaryLocation != null) {
await locationsRef
.doc(Constants.dbDocSecondLocation)
.set(_secondaryLocation!.toMap())
.then((value) => {
// update local values
_secondaryLocationFromDb = _secondaryLocation,
_secondLocationExists = true
});
} else if (_secondLocationExists) {
// secondLocationExists but is null here -> delete secondary in DB
await locationsRef.doc(Constants.dbDocSecondLocation).delete().then(
(doc) => {
2024-05-10 21:25:25 +02:00
// update local values
2024-05-17 23:08:26 +02:00
_secondaryLocationFromDb = null,
_secondLocationExists = false
},
onError: (e) => _showSnackBar("Error updating document: $e"),
);
}
2024-05-10 21:25:25 +02:00
}
2024-05-17 23:08:26 +02:00
// Save Languages - only if selected values changed
if (_selectedLanguages.isEmpty) {
_showSnackBar("No language selected");
return false;
} else if (_languagesFromDb.length != _selectedLanguages.length ||
_selectedLanguages
.any((element) => !_languagesFromDb.contains(element))) {
// Loop through each Language object and save it to the collection
for (int i = 0; i < _selectedLanguages.length; i++) {
// Convert Language object to a map and add the map to the collection,
// using .doc(myID).set() instead of .add() to avoid duplicates.
await languagesRef
.doc(_selectedLanguages[i].code)
.set(_selectedLanguages[i].toMap());
}
// update local variable (only if selection is not empty)
_languagesFromDb.clear();
_languagesFromDb.addAll(_selectedLanguages);
// List to store language codes from the provided list
List<String> languageCodes =
_selectedLanguages.map((language) => language.code).toList();
// Clean up languages that were not part of the provided list
await deleteUnusedDocuments(languagesRef, languageCodes);
2024-05-06 15:21:21 +02:00
}
2024-05-17 23:08:26 +02:00
return true;
} catch (e) {
_showSnackBar(e.toString());
return false;
2024-05-06 15:21:21 +02:00
}
}
/// Deletes documents from collection that are not part of the provided list
Future<void> deleteUnusedDocuments(
CollectionReference refCollection, List<String> idsToKeep) async {
// Fetch the existing documents from the database
QuerySnapshot snapshot = await refCollection.get();
// Loop through each document in the collection
for (QueryDocumentSnapshot doc in snapshot.docs) {
String documentId = doc.id;
// If the language code is not in the provided list, delete the document
if (!idsToKeep.contains(documentId)) {
await doc.reference.delete();
}
}
}
void updateSelectedGender(Set<Gender> newSelection) {
setState(() {
// By default there is only a single segment that can be
// selected at one time, so its value is always the first
// item in the selected set.
genderView = newSelection.first;
2024-05-05 01:02:09 +02:00
});
}
2024-05-10 00:21:23 +02:00
// Function to show location dialog
void _showLocationDialog(bool isPrimary) {
showDialog(
context: context,
builder: (BuildContext context) {
return LocationDialog(
onLocationSelected: (location) {
setState(() {
if (isPrimary) {
2024-05-10 21:25:25 +02:00
_mainLocation = location;
2024-05-10 00:21:23 +02:00
} else {
_secondaryLocation = location;
}
});
},
);
},
);
}
/// Method to remove secondary location
void _removeSecondaryLocation() {
setState(() {
_secondaryLocation = null;
});
}
2024-05-05 01:02:09 +02:00
@override
Widget build(BuildContext context) {
if (languagesList.isEmpty) {
return const Center(child: CircularProgressIndicator());
} else {
return Scaffold(
appBar: AppBar(
title: const Text("User Data"),
centerTitle: true,
),
2024-05-17 23:08:26 +02:00
drawer: const MyDrawer(),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: ListView(
children: [
if (widget.isRegProcess) ...[
const SizedBox(height: 10),
const Text(
'Please fill in the following fields to proceed with the registration process.',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 20),
const Divider(),
],
2024-05-10 00:21:23 +02:00
const SizedBox(height: 10),
2024-05-17 23:08:26 +02:00
const Text(
'Location',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
2024-05-10 21:25:25 +02:00
),
2024-05-17 23:08:26 +02:00
const SizedBox(height: 20),
// Display selected main location
2024-05-10 00:21:23 +02:00
const Text(
2024-05-17 23:08:26 +02:00
'Main Location:',
2024-05-10 00:21:23 +02:00
style: TextStyle(fontWeight: FontWeight.bold),
),
2024-05-17 23:08:26 +02:00
if (_mainLocation != null) ...[
Text(_mainLocation!.toString()),
const SizedBox(height: 10),
] else ...[
const Text('n/a'),
const SizedBox(height: 10),
],
// Button to set main location
Center(
child: ElevatedButton(
onPressed: () {
_showLocationDialog(true);
2024-05-08 00:59:16 +02:00
},
2024-05-17 23:08:26 +02:00
child: Text(_mainLocation != null
? 'Change Main Location'
: 'Set Main Location'),
2024-05-08 00:59:16 +02:00
),
2024-05-17 23:08:26 +02:00
),
const SizedBox(height: 20),
// Display selected secondary location
if (_secondaryLocation != null) ...[
const Text(
'Secondary Location:',
style: TextStyle(fontWeight: FontWeight.bold),
2024-05-06 15:21:21 +02:00
),
2024-05-17 23:08:26 +02:00
Text(_secondaryLocation!.toString()),
const SizedBox(height: 10),
],
if (_mainLocation != null) ...[
// Button to set secondary location
Center(
child: ElevatedButton(
onPressed: () {
_showLocationDialog(false);
},
child: Text(_secondaryLocation != null
? 'Change Secondary Location'
: 'Add Secondary Location'),
2024-05-10 21:25:25 +02:00
),
2024-05-17 23:08:26 +02:00
),
],
// Display selected secondary location or remove button
if (_secondaryLocation != null) ...[
Center(
child: ElevatedButton(
onPressed: _removeSecondaryLocation,
child: const Text('Remove Secondary Location'),
2024-05-10 21:25:25 +02:00
),
2024-05-17 23:08:26 +02:00
),
],
const SizedBox(height: 20),
const Text(
'Age',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
Row(
children: [
const Padding(padding: EdgeInsets.symmetric(horizontal: 8)),
Text(_selectedYear != null
? '${DateTime.now().year - (_selectedYear ?? 0)} years old'
: 'undefined age'),
const SizedBox(width: 20),
DropdownMenu(
initialSelection: _selectedYear,
onSelected: (int? newValue) {
setState(() {
_selectedYear = newValue;
});
},
dropdownMenuEntries: List.generate(50, (index) {
return DropdownMenuEntry<int>(
value: DateTime.now().year - 16 - index,
label: '${DateTime.now().year - 16 - index}',
);
}),
label: const Text('birth year'),
2024-05-10 21:25:25 +02:00
),
],
),
2024-05-17 23:08:26 +02:00
const SizedBox(height: 20),
Text(
'Gender (${genderView.name} selected)',
style:
const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
Center(
child: SegmentedButton<Gender>(
style: SegmentedButton.styleFrom(
selectedBackgroundColor: Colors.blue,
),
segments: const <ButtonSegment<Gender>>[
ButtonSegment<Gender>(
value: Gender.none,
label: Text('none'),
),
ButtonSegment<Gender>(
value: Gender.male,
label: Text('male'),
//icon: Icon(Icons.male_sharp),
),
ButtonSegment<Gender>(
value: Gender.female,
label: Text('female'),
//icon: Icon(Icons.female_sharp),
),
ButtonSegment<Gender>(
value: Gender.divers,
label: Text('divers'),
),
],
selected: <Gender>{genderView},
showSelectedIcon: false,
onSelectionChanged: updateSelectedGender,
),
),
const SizedBox(height: 20),
const Divider(),
Text(
'Language: (${_selectedLanguages.length} selected)',
style:
const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
...languagesList.map(buildSingleCheckbox), // ... spread operator
const Divider(),
Padding(
padding: const EdgeInsets.all(8.0),
child: MyButton(
text: widget.isRegProcess ? 'Save and continue' : "Save",
onTap: () async {
bool success = await saveUserData(context);
if (context.mounted) {
if (success) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SkillsForm(
isRegProcess: widget.isRegProcess,
skillsSought: false,
),
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Failed to save user data.'),
),
);
}
}
},
),
),
],
),
2024-05-05 01:02:09 +02:00
),
);
}
}
Widget buildSingleCheckbox(LanguageSetting languageSetting) => buildCheckbox(
languageSetting: languageSetting,
onClicked: () {
setState(() {
final newValue = !languageSetting.isSelected;
languageSetting.isSelected = newValue;
if (languageSetting.isSelected &&
!_selectedLanguages.contains(languageSetting.language)) {
_selectedLanguages.add(languageSetting.language);
} else if (languageSetting.isSelected == false) {
_selectedLanguages.removeWhere(
(element) => element.code == languageSetting.language.code);
}
});
},
);
Widget buildCheckbox({
required LanguageSetting languageSetting,
required VoidCallback onClicked,
}) =>
ListTile(
2024-05-06 15:21:21 +02:00
tileColor: Theme.of(context).colorScheme.secondary,
2024-05-05 01:02:09 +02:00
onTap: onClicked,
leading: SizedBox(
width: 48,
height: 32,
child: SvgPicture.asset(
languageSetting.language.iconFile,
),
),
title: Text(
languageSetting.language.nativeName,
style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
subtitle: Text(languageSetting.language.name),
trailing: Checkbox(
value: languageSetting.isSelected,
onChanged: (value) => onClicked(),
),
);
2024-05-17 23:08:26 +02:00
void _showSnackBar(String message) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(message),
backgroundColor: Colors.red,
action: SnackBarAction(
label: 'Dismiss',
onPressed: () {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
},
),
),
);
}
2024-05-05 01:02:09 +02:00
}