
import 'package:pshared/data/mapper/recipient/recipient.dart';
import 'package:pshared/models/recipient/recipient.dart';
import 'package:pshared/models/recipient/status.dart';
import 'package:pshared/models/recipient/type.dart';
import 'package:pshared/provider/organizations.dart';
import 'package:pshared/provider/template.dart';
import 'package:pshared/service/recipient/service.dart';


class RecipientsProvider extends GenericProvider<Recipient> {
  late OrganizationsProvider _organizations;
  String? _organizationRef;

  List<Recipient> get recipients => List<Recipient>.unmodifiable(items.toList()..sort((a, b) => a.storable.createdAt.compareTo(b.storable.createdAt))); 

  RecipientsProvider() : super(service: RecipientService.basicService);

  Future<Recipient> create({
    required String name,
    required String email,
  }) async => createObject(
    _organizations.current.id,
    newRecipient(
      organizationRef: _organizations.current.id, 
      email: email, 
      name: name, 
      status: RecipientStatus.ready, 
      type: RecipientType.internal,
    ).toDTO().toJson(),
  );

  void updateProviders(OrganizationsProvider organizations) {
    _organizations = organizations;
    if (!_organizations.isOrganizationSet) return;
    final organizationRef = _organizations.current.id;
    if (_organizationRef == organizationRef) return;
    _organizationRef = organizationRef;
    load(organizationRef, organizationRef);
  }
}
