89 lines
2.5 KiB
TypeScript
89 lines
2.5 KiB
TypeScript
import { Component, ChangeDetectionStrategy, inject, signal, computed, OnInit } from '@angular/core';
|
|
import { CommonModule } from '@angular/common';
|
|
import { DataService } from '../../core/services/data.service';
|
|
import { GroupDetailComponent } from './group-detail/group-detail.component';
|
|
|
|
@Component({
|
|
selector: 'app-groups',
|
|
standalone: true,
|
|
imports: [CommonModule, GroupDetailComponent],
|
|
templateUrl: './groups.component.html',
|
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
|
})
|
|
export class GroupsComponent implements OnInit {
|
|
private dataService = inject(DataService);
|
|
|
|
groups = this.dataService.userGroups;
|
|
friends = this.dataService.friends;
|
|
|
|
isCreating = signal(false);
|
|
newGroupName = signal('');
|
|
selectedFriendIds = signal<{ [key: string]: boolean }>({});
|
|
|
|
selectedGroupId = signal<string | null>(null);
|
|
|
|
isFormValid = computed(() => {
|
|
return this.newGroupName().trim().length > 0 && Object.keys(this.selectedFriendIds()).length > 0;
|
|
});
|
|
|
|
ngOnInit() {
|
|
this.dataService.loadGroups();
|
|
this.dataService.loadFriends();
|
|
this.dataService.loadUserBets();
|
|
}
|
|
|
|
selectGroup(groupId: string) {
|
|
this.selectedGroupId.set(groupId);
|
|
}
|
|
|
|
deselectGroup() {
|
|
this.selectedGroupId.set(null);
|
|
}
|
|
|
|
toggleCreateMode() {
|
|
this.isCreating.update(val => !val);
|
|
if (!this.isCreating()) {
|
|
this.resetForm();
|
|
}
|
|
}
|
|
|
|
onGroupNameChange(event: Event) {
|
|
this.newGroupName.set((event.target as HTMLInputElement).value);
|
|
}
|
|
|
|
onFriendSelect(friendId: string, event: Event) {
|
|
const isChecked = (event.target as HTMLInputElement).checked;
|
|
this.selectedFriendIds.update(currentIds => {
|
|
const newIds = { ...currentIds };
|
|
if (isChecked) {
|
|
newIds[friendId] = true;
|
|
} else {
|
|
delete newIds[friendId];
|
|
}
|
|
return newIds;
|
|
});
|
|
}
|
|
|
|
async createGroup() {
|
|
if (!this.isFormValid()) {
|
|
return;
|
|
}
|
|
const selectedIds = Object.keys(this.selectedFriendIds());
|
|
const selectedMembers = this.friends().filter(f => selectedIds.includes(f.id));
|
|
const currentUser = this.dataService.currentUser();
|
|
if (!currentUser) return;
|
|
|
|
const allMembers = [currentUser, ...selectedMembers];
|
|
const uniqueMembers = [...new Map(allMembers.map(item => [item['id'], item])).values()];
|
|
|
|
await this.dataService.addGroup(this.newGroupName(), uniqueMembers);
|
|
|
|
this.toggleCreateMode();
|
|
}
|
|
|
|
private resetForm() {
|
|
this.newGroupName.set('');
|
|
this.selectedFriendIds.set({});
|
|
}
|
|
}
|