cofounderella/lib/services/user_service.dart

90 lines
2.8 KiB
Dart

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import '../constants.dart';
import '../enumerations.dart';
class UserService {
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
Future<void> saveUserData(UserCredential userCredential, String email,
String firstname, String lastname) async {
// create full name
String fullName = (firstname.isNotEmpty && lastname.isNotEmpty)
? '$firstname $lastname'
: (firstname.isNotEmpty
? firstname
: (lastname.isNotEmpty ? lastname : ''));
// save user info to users document
await _firestore
.collection(Constants.dbCollectionUsers)
.doc(userCredential.user!.uid)
.set(
{
Constants.dbFieldUsersID: userCredential.user!.uid,
Constants.dbFieldUsersEmail: email,
Constants.dbFieldUsersFirstName: firstname,
Constants.dbFieldUsersLastName: lastname,
Constants.dbFieldUsersName: fullName,
},
);
}
Future<List<SkillOption>> getSkillsFromFirebase(
bool skillsSought, String userId) async {
// Fetch skills from Firestore
DocumentSnapshot userDoc = await _firestore
.collection(Constants.dbCollectionUsers)
.doc(userId)
.get();
if (userDoc.exists && userDoc.data() != null) {
Map<String, dynamic> userData =
userDoc.data()! as Map<String, dynamic>; // Explicit cast
List<dynamic>? skills;
if (skillsSought) {
skills = userData[Constants.dbFieldUsersSkillsSought];
} else {
skills = userData[
Constants.dbFieldUsersSkills]; //as List<dynamic>?; // Explicit cast
}
if (skills != null && skills.isNotEmpty) {
// Convert skills from strings to enum values
List<SkillOption> userSkills = skills
.map((skill) => SkillOption.values
.firstWhere((x) => x.toString() == 'SkillOption.$skill'))
.toList();
return userSkills;
}
}
return [];
}
Future<bool> saveSkillsToFirebase(List<SkillOption> selectedOptions,
bool skillsSought, String userId) async {
try {
// Convert enum values to strings, removing leading EnumType with split
List<String> skills = selectedOptions
.map((option) => option.toString().split('.').last)
.toList();
// Update the corresponding 'skills' field in the user's document
String keyToUpdate = skillsSought
? Constants.dbFieldUsersSkillsSought
: Constants.dbFieldUsersSkills;
_firestore
.collection(Constants.dbCollectionUsers)
.doc(userId)
.update({keyToUpdate: skills});
return true;
} catch (e) {
return false;
}
}
}