import 'dart:convert';

import 'package:excelso_attendance/helper/logger.dart';
import 'package:excelso_attendance/main.dart';
import 'package:excelso_attendance/models/branch.dart';
import 'package:http/http.dart' as http;

String baseUrl = "";
String endPoint = "rav/attendance/";

class Api {
  static Future<Map<String, dynamic>> getNearestBranch() async {
    String apiUrl = "$baseUrl${endPoint}nearest_branch_list";
    Map<String, dynamic> result;

    try {
      dynamic jsonObject =
          await httpRequest(typePost, apiUrl, "getNearestBranch");
      if (jsonObject == false) {
        result = {"error": true, "msg": "Can't connect to server"};
        return result;
      } else {
        List<BranchModel> branchList = [];

        List<dynamic> branchs = jsonObject['data']['branch_list'];
        for (int i = 0; i < branchs.length; i++) {
          branchList.add(
            BranchModel.json(
              branchs[i],
            ),
          );
        }

        result = {
          "error": false,
          "msg": "Success get data",
          "branchs": branchList,
        };
        return result;
      }
    } catch (e) {
      result = {
        "error": true,
        "msg": "Something wrong with our server, try again later"
      };
      return result;
    }
  }
}

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;
  }
}
