 }
 
 struct Spotify {
-  private static func realApiRequest(_ route: String, method: HTTPMethod? = nil, body: Data? = nil) -> JSONResponse {
+  var db: DB
+
+  var credentials: Credentials {
+    return db.credentials
+  }
+
+  init() {
+    self.db = DB.load()
+  }
+
+  private func realApiRequest(_ route: String, method: HTTPMethod? = nil, body: Data? = nil) -> JSONResponse {
     return Utils.synchronousRequest(
       "https://api.spotify.com/v1/\(route)",
-      headers: ["Authorization": "Bearer \(Credentials.load().accessToken)"],
+      headers: ["Authorization": "Bearer \(credentials.accessToken)"],
       method: method,
       body: body
     )
   }
 
-  private static func apiRequest(_ route: String, method: HTTPMethod? = nil, body: Data? = nil) -> JSONResponse {
+  mutating private func apiRequest(_ route: String, method: HTTPMethod? = nil, body: Data? = nil) -> JSONResponse {
     let initialResult = realApiRequest(route, method: method, body: body)
 
     if initialResult.0["error"] != nil {

    }
  }

  private static func refreshTokenAndSave() {
    let newToken = refreshToken()

    _ = Credentials.updateAccessToken(newToken)
  }

  static func currentlyPlaying() -> JSONResponse {
    return Spotify.apiRequest("me/player/currently-playing")
  }

  static func saveToLibrary() -> JSONResponse {
    let currentlyPlaying = Spotify.currentlyPlaying().json
    let item = currentlyPlaying["item"] as! [String: Any]
    let id = item["id"] as! String
    print(item["name"] as! String)
    let body = try! JSONEncoder().encode(["ids": [id]])
    return Spotify.apiRequest("me/tracks", method: .PUT, body: body)
  }
}


  var accessToken: String
  var clientId: String
  var clientSecret: String
}


struct DB: Codable {
  var credentials: Credentials
  var playlistIds: [String: String]

  static let file = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".sptf.json")

  static func load() -> DB {
    let fileData = try! Data(contentsOf: DB.file)
    return try! JSONDecoder().decode(DB.self, from: fileData)
  }

  static func updateCredentials(_ newCredentials: Credentials) -> DB {
    var existingDb = DB.load()
    existingDb.credentials = newCredentials

    let json = try! JSONEncoder().encode(existingDb)
    let output = String(data: json, encoding: .ascii)!

    try! output.write(to: DB.file, atomically: true, encoding: .ascii)

    return existingDb
  }
}

