import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:tour_travel_agr/helper/logger.dart';
import 'package:tour_travel_agr/main.dart';

class ApiResponse {
  bool error;
  String msg;
  dynamic data;

  ApiResponse({
    required this.error,
    required this.msg,
    this.data,
  });
}

int typeGet = 1;
int typePost = 2;

Future<dynamic> httpRequest(int typeRequest, String apiUrl, String namaFungsi,
    {String? bodies = ''}) async {
  dynamic apiResult;
  if (typeRequest == typePost) {
    apiResult = await http.post(Uri.parse(apiUrl),
        headers: {"Content-Type": "application/json"}, body: bodies);
  } else if (typeRequest == typeGet) {
    apiResult = await http.get(
      Uri.parse(apiUrl),
      headers: {"Content-Type": "application/json"},
    );
  } else {
    if (debug) {
      logd('HTTP REQUEST', 'TIPE REQUEST TIDAK VALID');
    }
    return false;
  }
  if (apiResult.statusCode == 200 || apiResult.statusCode == 401) {
    var jsonObject = jsonDecode(apiResult.body);
    return jsonObject;
  } else {
    if (debug) {
      logd('API CLASS ON API.DART, FUNGSI: $namaFungsi, URL : $apiUrl',
          'ERROR CONNECT TO SERVER, RESPONSE CODE : ${apiResult.statusCode}');
    }
    return false;
  }
}
