import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:jiffy/jiffy.dart';
import '../apiError.dart';
import '../apiRequest.dart';

abstract class MhslApi<T> extends ApiRequest {
  String subpath;
  MhslApi(this.subpath);

  http.Response? response;

  Future<http.Response>? request(Uri uri);
  T assemble(String raw);

  Future<T> run() async {
    var endpoint = Uri.parse('https://mhsl.eu/marianum/marianummobile/$subpath');

    var data = await request(endpoint);
    if(data == null) {
      throw ApiError('Request could not be dispatched!');
    }

    if(data.statusCode > 299) {
      throw ApiError('Non 200 Status code from mhsl services: $subpath: ${data.statusCode}');
    }

    return assemble(utf8.decode(data.bodyBytes));
  }

  static String dateTimeToJson(DateTime time) => Jiffy.parseFromDateTime(time).format(pattern: 'yyyy-MM-dd HH:mm:ss');
  static DateTime dateTimeFromJson(String time) => DateTime.parse(time);
}
