import 'package:dio/dio.dart';
import 'Result.dart';
import 'package:intl/intl.dart';

class HttpManager {
  // static String baseUrl = 'http://117.81.233.142:8206/';
  // static String baseUrl='http://192.168.50.15:8080/';

  static String baseUrl = 'http://202.79.174.56:8206/';
  static String token;
  static bool debug;

  static Dio _createDio() {
    Map<String, dynamic> headers = <String, dynamic>{};
    headers['token'] = token;
    BaseOptions options = BaseOptions(baseUrl: baseUrl, headers: headers);
    return Dio(options);
  }

  static Future<Result> post(String url, {Map<String, dynamic> data}) async {
    Result result = Result.empty();
    try {
      FormData formData = FormData.from(data ?? {});
      Response response = await _createDio().post(url, data: formData);
      print(response);
      if (response.statusCode != 200) {
        result.success = false;
        result.error = 'httpCode' + response.statusCode.toString();
        return result;
      }
      result = Result.fromJson(response.data);
      return result;
    } catch (e) {
      result.success = false;
      result.error = e.toString();
    }
    return result;
  }

  static Future<Result> get(String url, {Map<String, dynamic> data}) async {
    Result result = Result.empty();
    try {
      Response response = await _createDio().get(url, queryParameters: data ?? {});
      if (response.statusCode != 200) {
        result.success = false;
        result.error = 'httpCode' + response.statusCode.toString();
        return result;
      }
      result = Result.fromJson(response.data);
      return result;
    } catch (e) {
      result.success = false;
      result.error = e.toString();
    }
    return result;
  }
}

String readTimestamp(int timestamp, String _timeType) {
  return DateFormat(_timeType).format(DateTime.fromMillisecondsSinceEpoch(timestamp));
}
