11import UIKit
22import Yosemite
3+ import protocol Storage. StorageManagerType
34
45protocol SwitchStoreUseCaseProtocol {
56 func switchStore( with storeID: Int64 , onCompletion: @escaping ( Bool ) -> Void )
@@ -10,9 +11,19 @@ protocol SwitchStoreUseCaseProtocol {
1011final class SwitchStoreUseCase : SwitchStoreUseCaseProtocol {
1112
1213 private let stores : StoresManager
14+ private let storageManager : StorageManagerType
1315
14- init ( stores: StoresManager ) {
16+ private lazy var resultsController : ResultsController < StorageSite > = {
17+ return ResultsController ( storageManager: storageManager, sortedBy: [ ] )
18+ } ( )
19+
20+ private var wooCommerceSites : [ Site ] {
21+ resultsController. fetchedObjects. filter { $0. isWooCommerceActive == true }
22+ }
23+
24+ init ( stores: StoresManager , storageManager: StorageManagerType = ServiceLocator . storageManager) {
1525 self . stores = stores
26+ self . storageManager = storageManager
1627 }
1728
1829 /// The async version of `switchStore` that wraps the completion block version.
@@ -28,6 +39,25 @@ final class SwitchStoreUseCase: SwitchStoreUseCaseProtocol {
2839 }
2940 }
3041
42+ /// Switches the to store with the given id if it was previously synced and stored.
43+ /// This is done to check whether the user has access to that store, avoiding undetermined states if we log out
44+ /// from the current one and try to switch to a store they don't have access to.
45+ ///
46+ /// - Parameter storeID: target store ID.
47+ /// - Returns: a boolean that indicates whether the site was changed.
48+ ///
49+ func switchToStoreIfSiteIsStored( with storeID: Int64 , onCompletion: @escaping ( Bool ) -> Void ) {
50+ refreshStoredSites ( )
51+
52+ let siteWasStored = wooCommerceSites. first ( where: { $0. siteID == storeID } ) != nil
53+
54+ guard siteWasStored else {
55+ return onCompletion ( false )
56+ }
57+
58+ switchStore ( with: storeID, onCompletion: onCompletion)
59+ }
60+
3161 /// A static method which allows easily to switch store. The boolean argument in `onCompletion` indicates that the site was changed.
3262 /// When `onCompletion` is called, the selected site ID is updated while `Site` might still not be available if the site does not exist in storage yet
3363 /// (e.g. a newly connected site).
@@ -111,4 +141,8 @@ final class SwitchStoreUseCase: SwitchStoreUseCaseProtocol {
111141
112142 AppDelegate . shared. authenticatorWasDismissed ( )
113143 }
144+
145+ private func refreshStoredSites( ) {
146+ try ? resultsController. performFetch ( )
147+ }
114148}
0 commit comments