#if ANDROID || IOS using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Maui.ApplicationModel.Communication; using Microsoft.Maui.ApplicationModel; using Microsoft.Maui.Devices; using PostIt.Services; using System.Linq; namespace PostIt.Android.Services; /// /// Mobile implementation backed by MAUI Essentials /// Contacts.Default. /// /// Compiled only for ANDROID and IOS. On desktop targets, /// see ContactService.Desktop.cs (the stub that wins at /// compile time). /// /// Note: at runtime, this class throws /// NotImplementedInReferenceAssemblyException unless /// the host application project also references the /// platform-specific Microsoft.Maui.Essentials implementation /// (typically PostIt.Android). On iOS the same is /// required via PostIt.iOS. On desktop the stub is used /// and this file is excluded. /// public sealed class ContactService : IContactService { public async Task> GetDeviceContactsAsync(CancellationToken ct = default) { if (DeviceInfo.Current.Platform == DevicePlatform.Unknown) return Array.Empty(); try { var status = await Permissions.RequestAsync(); if (status != PermissionStatus.Granted) return Array.Empty(); var contacts = await Contacts.Default.GetAllAsync(); if (contacts is null) return Array.Empty(); // Carry the per-contact email list as-is. A real // device contact can carry several addresses (home / // work / other); the UI use case ("invite / add to a // circle") can then decide which address to use, or // let the user pick. The platform-neutral ContactDto // shape is intentionally richer than the Yavsc // directory's single-Email shape — the two flows // answer different questions. var result = new List(contacts.Count()); foreach (var c in contacts) { var emails = ExtractEmails(c.Emails); result.Add(new ContactDto( c.Id, c.DisplayName ?? string.Empty, emails)); } return result; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"ContactService: {ex.Message}"); return Array.Empty(); } } private static IReadOnlyList ExtractEmails(IEnumerable? emails) { if (emails is null) return Array.Empty(); var list = new List(); foreach (var e in emails) { if (!string.IsNullOrEmpty(e.EmailAddress)) list.Add(e.EmailAddress); } return list; } } #endif