import 'package:http/http.dart' as http;
import 'package:marianum_mobile/api/apiError.dart';
import 'package:marianum_mobile/api/apiRequest.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../apiParams.dart';

enum TalkApiMethod {
  get,
  post,
  put,
  delete,
}

abstract class TalkApi<T> extends ApiRequest {
  String path;
  ApiParams? body;
  Map<String, String>? headers = {};
  Map<String, dynamic>? getParameters;

  http.Response? response;

  TalkApi(this.path, this.body, {this.headers, this.getParameters});

  Future<http.Response>? request(Uri uri, ApiParams? body, Map<String, String>? headers);
  T assemble(String raw);

  Future<T> run() async {
    getParameters?.forEach((key, value) {
      getParameters?.update(key, (value) => value.toString());
    });

    SharedPreferences preferences = await SharedPreferences.getInstance();

    Uri endpoint = Uri.https("${preferences.getString("username")!}:${preferences.getString("password")!}@cloud.marianum-fulda.de", "/ocs/v2.php/apps/spreed/api/$path", getParameters);

    headers ??= {};
    headers?.putIfAbsent("Accept", () => "application/json");
    headers?.putIfAbsent("OCS-APIRequest", () => "true");

    http.Response? data = await request(endpoint, body, headers);
    if(data == null) {
      throw ApiError("Request could not be dispatched!");
    }
    //dynamic jsonData = jsonDecode(data.body);


    return assemble(data.body);
  }

}