import 'package:flutter/material.dart';

import 'package:collection/collection.dart';

import 'package:pshared/models/organization/employee.dart';
import 'package:pshared/provider/organizations.dart';
import 'package:pshared/provider/resource.dart';
import 'package:pshared/service/accounts/employees.dart';
import 'package:pshared/utils/exception.dart';


class EmployeesProvider extends ChangeNotifier {

  Resource<List<Employee>> _employees = Resource<List<Employee>>(data: []);
  List<Employee> get employees => _employees.data ?? [];
  bool get isLoading => _employees.isLoading;
  Object? get error => _employees.error;
  Employee? getEmployee(String? employeeRef) => employees.firstWhereOrNull((employee) => employee.id == employeeRef);


  bool Function(Employee)? _filterPredicate;

  List<Employee> get filteredItems => _filterPredicate != null 
    ? employees.where(_filterPredicate!).toList() 
    : employees;

  void setFilterPredicate(bool Function(Employee)? predicate) {
    _filterPredicate = predicate;
    notifyListeners();
  }

  void clearFilter() => setFilterPredicate(null);

  void updateProviders(OrganizationsProvider organizations) {
    load(organizations.current.id);
  }

  Future<List<Employee>> load(String organizationRef) async {
    _employees = _employees.copyWith(isLoading: true, error: null);
    notifyListeners();

    try {
      final fetchedEmployees = await EmployeesService.list(organizationRef);
      _employees = _employees.copyWith(
        data: fetchedEmployees,
        isLoading: false,
        error: null,
      );
    } catch (e) {
      _employees = _employees.copyWith(error: toException(e), isLoading: false);
    }

    notifyListeners();
    return employees;
  }
}
