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

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

class IOClientWithCookies extends IOClient {
  BaseStorageClient _storage;

  IOClientWithCookies(BaseStorageClient storage) {
    _storage = storage;
  }

  @override
  Future<IOStreamedResponse> 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"]);
      }

      _accessToken = await _storage.get("accessToken");
      _refreshToken = await _storage.get("refreshToken");

      print("Access Token: $_accessToken");
      print("Refresh Token: $_refreshToken");

      return response;
    });
  }
}
