From f292874809439a2e08d07ed763930b53f30193a5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bruno=20Pantale=C3=A3o=20Gon=C3=A7alves?=
 <bruno.ing879@gmail.com>
Date: Thu, 7 Dec 2023 10:11:01 -0300
Subject: [PATCH] Request preferred thread network credential alongside all
 credentials (#2473)

<!-- Thank you for submitting a Pull Request and helping to improve Home
Assistant. Please complete the following sections to help the processing
and review of your changes. Please do not delete anything from this
template. -->

## Summary
<!-- Provide a brief summary of the changes you have made and most
importantly what they aim to achieve -->
Request preferred thread network credential alongside all credentials,
since preferred credentials trigger a privacy permission dialog that may
be necessary to get all credentials later on.

## Screenshots
<!-- If this is a user-facing change not in the frontend, please include
screenshots in light and dark mode. -->

## Link to pull request in Documentation repository
<!-- Pull requests that add, change or remove functionality must have a
corresponding pull request in the Companion App Documentation repository
(https://github.com/home-assistant/companion.home-assistant). Please add
the number of this pull request after the "#" -->
Documentation: home-assistant/companion.home-assistant#

## Any other notes
<!-- If there is any other information of note, like if this Pull
Request is part of a bigger change, please include it here. -->
---
 Sources/App/Resources/en.lproj/Localizable.strings    |  1 +
 .../ThreadClientService.swift                         | 11 ++++++++++-
 .../ThreadCredentialsSharingView.swift                |  4 ++--
 Sources/Shared/Resources/Swiftgen/Strings.swift       |  2 ++
 4 files changed, 15 insertions(+), 3 deletions(-)

diff --git a/Sources/App/Resources/en.lproj/Localizable.strings b/Sources/App/Resources/en.lproj/Localizable.strings
index f7526ca91..38f75691c 100644
--- a/Sources/App/Resources/en.lproj/Localizable.strings
+++ b/Sources/App/Resources/en.lproj/Localizable.strings
@@ -775,3 +775,4 @@ Home Assistant is free and open source home automation software with a focus on
 "thread.credentials.border_agent_id_title" = "Border Agent ID";
 "thread.credentials.share_credentials_button_title" = "Share credential with Home Assistant";
 "thread.credentials.screen_title" = "Thread Credentials";
+"thread.credentials.no_credential_available" = "You don't have credentials available on your iCloud Keychain.";
diff --git a/Sources/App/ThreadCredentialsSharing/ThreadClientService.swift b/Sources/App/ThreadCredentialsSharing/ThreadClientService.swift
index 9f8ed2e43..b524bf831 100644
--- a/Sources/App/ThreadCredentialsSharing/ThreadClientService.swift
+++ b/Sources/App/ThreadCredentialsSharing/ThreadClientService.swift
@@ -28,7 +28,16 @@ final class ThreadClientService: THClientProtocol {
 
     func retrieveAllCredentials() async throws -> [ThreadCredential] {
         let placeholder = "Unknown"
-        return try await client.allCredentials().map { credential in
+
+        // Thre preferred credential call is necessary as it triggers a permission dialog
+        let preferredCredential = try await client.preferredCredentials()
+
+        // All credentials retrieve the rest of the credentials after user acceps permission dialog
+        var allCredentials = try await client.allCredentials()
+        allCredentials = allCredentials.filter { $0.borderAgentID != preferredCredential.borderAgentID }
+        allCredentials.insert(preferredCredential)
+
+        return allCredentials.map { credential in
             ThreadCredential(
                 networkName: credential.networkName ?? placeholder,
                 networkKey: credential.networkKey?.hexadecimal ?? placeholder,
diff --git a/Sources/App/ThreadCredentialsSharing/ThreadCredentialsSharingView.swift b/Sources/App/ThreadCredentialsSharing/ThreadCredentialsSharingView.swift
index 1ecb5d745..c760f275f 100644
--- a/Sources/App/ThreadCredentialsSharing/ThreadCredentialsSharingView.swift
+++ b/Sources/App/ThreadCredentialsSharing/ThreadCredentialsSharingView.swift
@@ -21,7 +21,6 @@ struct ThreadCredentialsSharingView: View {
             }
             .navigationTitle(L10n.Thread.Credentials.screenTitle)
             .navigationBarTitleDisplayMode(.inline)
-            .background(Color(uiColor: .secondarySystemBackground))
             .toolbar(content: {
                 ToolbarItem(placement: .topBarTrailing) {
                     Button {
@@ -85,7 +84,7 @@ struct ThreadCredentialsSharingView: View {
     @ViewBuilder
     private var credentialsList: some View {
         if viewModel.credentials.isEmpty {
-            Text("You don't have credentials available on your iCloud Keychain.")
+            Text(L10n.Thread.Credentials.noCredentialAvailable)
                 .multilineTextAlignment(.center)
         } else {
             List(viewModel.credentials, id: \.borderAgentID) { credential in
@@ -94,6 +93,7 @@ struct ThreadCredentialsSharingView: View {
                     .listRowBackground(Color.clear)
             }
             .listStyle(.plain)
+            .background(Color(uiColor: .secondarySystemBackground))
         }
     }
 
diff --git a/Sources/Shared/Resources/Swiftgen/Strings.swift b/Sources/Shared/Resources/Swiftgen/Strings.swift
index 627d428ee..9856e35e5 100644
--- a/Sources/Shared/Resources/Swiftgen/Strings.swift
+++ b/Sources/Shared/Resources/Swiftgen/Strings.swift
@@ -1769,6 +1769,8 @@ public enum L10n {
       public static var networkKeyTitle: String { return L10n.tr("Localizable", "thread.credentials.network_key_title") }
       /// Network Name
       public static var networkNameTitle: String { return L10n.tr("Localizable", "thread.credentials.network_name_title") }
+      /// You don't have credentials available on your iCloud Keychain.
+      public static var noCredentialAvailable: String { return L10n.tr("Localizable", "thread.credentials.no_credential_available") }
       /// Thread Credentials
       public static var screenTitle: String { return L10n.tr("Localizable", "thread.credentials.screen_title") }
       /// Share credential with Home Assistant