 
 import SwiftyJSON
 import FeedlyKit
-import NXOAuth2Client
+import OAuthSwift
+import Prephirences
+
+open class FeedlyOAuthRequestRetrier: OAuthRequestRetrier {
+    public override func refreshed(_ succeeded: Bool) {
+        if succeeded {
+            CloudAPIClient.credential = oauth.client.credential
+            CloudAPIClient.setAccessToken(oauth.client.credential.oauthToken)
+        } else {
+            CloudAPIClient.credential = nil
+            CloudAPIClient.logout()
+        }
+    }
+}
+
 
 public extension CloudAPIClient {
     fileprivate static let userDefaults = UserDefaults.standard
-    fileprivate static var oauth2clientDelegate = FeedlyOAuth2ClientDelegate()
-    fileprivate static var _account:                    NXOAuth2Account?
     fileprivate static var _profile:                    Profile?
     fileprivate static var _notificationDateComponents: DateComponents?
     fileprivate static var _lastChecked:                Date?

    }

    fileprivate static func clearAllAccount() {
        guard let store    = NXOAuth2AccountStore.sharedStore() as? NXOAuth2AccountStore else { return }
        guard let accounts = store.accounts as? [NXOAuth2Account]                        else { return }
        for account in accounts {
            if account.accountType == "Feedly" {
                store.removeAccount(account)
            }
        }
        _account = nil
        profile = nil
    }
    
    fileprivate static func loadConfig() {


    public static func setup() {
        loadConfig()
        oauth = OAuth2Swift(
            consumerKey:    clientId,
            consumerSecret: clientSecret,
            authorizeUrl:   shared.authUrl,
            accessTokenUrl: shared.tokenUrl,
            responseType:   "code"
        )
        if let c = credential {
            oauth.client.credential.oauthToken          = c.oauthToken
            oauth.client.credential.oauthTokenSecret    = c.oauthTokenSecret
            oauth.client.credential.oauthTokenExpiresAt = c.oauthTokenExpiresAt
            oauth.client.credential.oauthRefreshToken   = c.oauthRefreshToken
        }
        if let p = profile, let c = credential {
            CloudAPIClient.login(profile: p, token: c.oauthToken)
        }
        shared.manager.retrier = FeedlyOAuthRequestRetrier(oauth)
        CloudAPIClient.sharedPipe.0.observeResult({ result in
            guard let event = result.value else { return }
            switch event {
            case .Login(let profile):
                self.profile = profile
            case .Logout:
                self.profile = nil
                self.credential = nil
            }
        })
    }
}
