// lib/utils/activity_file_parser.dart
import 'dart:convert';
import 'dart:typed_data';

import 'package:aves/model/activity/activity_track.dart';

import 'fit_activity_parser.dart';
import 'gpx_activity_parser.dart';
import 'tcx_activity_parser.dart';

class ActivityFileParser {
  static bool isSupportedFileName(String name) {
    final lower = name.toLowerCase().trim();

    return lower.endsWith('.fit') ||
        lower.endsWith('.gpx') ||
        lower.endsWith('.tcx');
  }

  static Future<ActivityTrack?> parse(
    Uint8List bytes, {
    required String fileName,
    String? xml,
  }) async {
    final lower = fileName.toLowerCase().trim();

    try {
      if (lower.endsWith('.fit')) {
        return FitActivityParser.parse(bytes, fileName: fileName);
      }

      if (lower.endsWith('.gpx')) {
        final text = xml ?? utf8.decode(bytes, allowMalformed: true);
        if (text.trim().isEmpty) return null;

        return GpxActivityParser.parse(text, fileName: fileName);
      }

      if (lower.endsWith('.tcx')) {
        final text = xml ?? utf8.decode(bytes, allowMalformed: true);
        if (text.trim().isEmpty) return null;

        return TcxActivityParser.parse(text, fileName: fileName);
      }

      return null;
    } catch (_) {
      return null;
    }
  }
}
