import 'dart:convert';
import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:timeago/timeago.dart' as timeago;
import 'lat_lng.dart';
import 'place.dart';
import 'uploaded_file.dart';

String? convertToUppercase(String input) {
  return input.toUpperCase();
}

String? uploadFileToBase64(String? uploadFile) {
  if (uploadFile == null) {
    return null;
  }

  final List<int> bytes = uploadFile.codeUnits;

  final String base64String = base64.encode(bytes);

  return base64String;
}

String jsonListToStr(List<dynamic> visitorList) {
  String result = '';
  for (var visitor in visitorList) {
    result += '${visitor['VTE_DOCUMENTO']},';
  }
  return result.substring(0, result.length - 1);
}

Future<Map<String, String>> stringToMap(String v) async {
  try {
    return Future.value(Map.fromEntries(
      v.split(',').map((part) {
        final keyValue = part.split(':');
        if (keyValue.length < 2) {
          throw FormatException('Invalid key-value pair: $part of $v');
        }
        final key = keyValue[0].trim();
        final value = keyValue
            .sublist(1)
            .join(':')
            .trim(); // Join the remaining parts to handle DateTime correctly
        return MapEntry(key, value);
      }),
    ));
  } catch (e) {
    print('Error parsing string to map: $e');
    return Future.value({});
  }
}

List<dynamic> listStrJsonToJsonList(
  dynamic jsonList,
  List<String> strList,
) {
  List<dynamic> result = [];

  for (int i = 0; i < jsonList.length; i++) {
    Map<String, dynamic> item = jsonList[i];
    if (i < strList.length) {
      item['newField'] = strList[i];
    } else {
      item['newField'] = '';
    }
    result.add(item);
  }

  return result;
}

String strListToStr(List<String> strList) {
  return strList.join(',');
}

int extractIdToStr(String str) {
  final idStart = str.indexOf('_ID:') + 4;
  final idEnd = str.indexOf(',', idStart);
  final idStr = str.substring(idStart, idEnd);
  return int.parse(idStr);
}

String extractDescToStr(String str) {
  final startIndex = str.indexOf('_DESCRICAO:') + '_DESCRICAO:'.length;
  final endIndex = str.indexOf(',', startIndex);
  return str.substring(startIndex, endIndex);
}

String jsonToStr(dynamic json) {
  String jsonString = jsonEncode(json);
  return jsonString;
}

Stream<double> getProgressValue() {
  final startTime = DateTime.now().millisecondsSinceEpoch;
  final endTime = startTime + 20000;
  final duration = Duration(milliseconds: 100);
  return Stream.periodic(duration, (int count) {
    final currentTime = DateTime.now().millisecondsSinceEpoch;
    final elapsedTime = currentTime - startTime;
    final progress = math.max(0.0, 1.0 - (elapsedTime / (endTime - startTime)));
    return progress;
  });
}
