using System.Collections.ObjectModel;
using WPFBeginner.Models;

namespace WPFBeginner.Services;

public interface IMemberService
{
    ObservableCollection<Member> Members { get; }
    void LoadDefaultMembers(List<Member> defaultMembers);
    void Add(Member member);
    void Remove(Member member);
    void Reset();
    IEnumerable<Member> Search(string keyword);
}

public class MemberService : IMemberService
{
    private readonly List<Member> _defaultMembers = new();
    public ObservableCollection<Member> Members { get; } = new();

    public void LoadDefaultMembers(List<Member> defaultMembers)
    {
        _defaultMembers.Clear();
        _defaultMembers.AddRange(defaultMembers.Select(m => m.Clone()));
        Reset();
    }

    public void Add(Member member)
    {
        Members.Add(member);
    }

    public void Remove(Member member)
    {
        Members.Remove(member);
    }

    public void Reset()
    {
        Members.Clear();
        foreach (var member in _defaultMembers)
        {
            Members.Add(member.Clone());
        }
    }

    public IEnumerable<Member> Search(string keyword)
    {
        if (string.IsNullOrWhiteSpace(keyword))
        {
            return Members;
        }

        var lowerKeyword = keyword.ToLower();
        return Members.Where(m =>
            m.Name.ToLower().Contains(lowerKeyword) ||
            m.Call.ToLower().Contains(lowerKeyword) ||
            m.EMail.ToLower().Contains(lowerKeyword) ||
            m.No.ToLower().Contains(lowerKeyword));
    }
}
