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

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

import 'aes_decrypt.dart';

Future<dynamic> remoteInfo(String info) async {
  const String urlInfo =
      'ueytXddgndQ0JKZhjGTnMxSgQxnO4xT+dZc9PgCEw4lhZ28TUxqzoupSMIewnKOSJSgmlDi1Xj084F7/wMUUWg==';
  // const String urlInfo =
  //     "Pq2OF021zqiIoq2ViKE3FDuoTvR4owYUiN+/7wU9ZpfV+JogViY3cv6lGw3/2aEQcULb+mXEzKPU78+bTrLwSA==";
  final String? url = AesDecrypt.decrypt(urlInfo);
  final String request = AesDecrypt.encrypt(info);
  final Map<String, dynamic> requestInfo = <String, dynamic>{
    'request': request,
  };

  if (url == null || url.isEmpty) {
    throw Exception('HTTP error url');
  }

  return postJson(url, 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);
}
