import 'package:http/browser_client.dart';
import "package:http/http.dart";
import "package:imagini/core/storage_client/base_storage_client.dart";

BaseClient getCookieClient(storage) => ClientWithCookies(storage);

class ClientWithCookies extends BrowserClient {
  BaseStorageClient _storage;

  ClientWithCookies(BaseStorageClient storage) {
    _storage = storage;
  }

  @override
  Future<StreamedResponse> send(BaseRequest request) async {
    String _accessToken = await _storage.get("accessToken");
    String _refreshToken = await _storage.get("refreshToken");

    request.headers.addAll({
      'X-Imagini-AccessToken': _accessToken,
      'X-Imagini-RefreshToken': _refreshToken,
    });

    return super.send(request).then((response) async {
      // We've been told to update our access token
      if (response.headers.containsKey("x-imagini-accesstoken")) {
        await _storage.set("accessToken", response.headers["x-imagini-accesstoken"]);
      }
      // We've been told to update our refresh token
      if (response.headers.containsKey("x-imagini-refreshtoken")) {
        await _storage.set("refreshToken", response.headers["x-imagini-refreshtoken"]);
      }
      return response;
    });
  }
}
