import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:guru_utils/log/log.dart';
import 'package:http_parser/http_parser.dart';

///  Created by Haoyi on 2021-06-3.
///
class CustomTransformer extends DefaultTransformer {
  CustomTransformer() : super(jsonDecodeCallback: _parseJson);

  @override
  Future<String> transformRequest(RequestOptions options) async {
    var data = options.data ?? '';
    if (data is! String) {
      if (_isJsonMime(options.contentType)) {
        return await _encodeToJson(options.data);
      } else if (data is Map<String, dynamic>) {
        return Transformer.urlEncodeMap(data);
      }
    }
    return data.toString();
  }

  bool _isJsonMime(String? contentType) {
    if (contentType == null) return false;
    return MediaType.parse(contentType).mimeType.toLowerCase() == Headers.jsonMimeType.mimeType;
  }

  Future<String> _encodeToJson(dynamic data) async {
    return await compute(jsonEncode, data);
  }
}

// Must be top-level function
_parseAndDecode(String response) {
  return jsonDecode(response);
}

_parseJson(String text) {
  return compute(_parseAndDecode, text);
}

platformLogPrint(Object object) {
  Log.v("[NETWORK] " + object.toString());
}
