import 'package:dart_framework/subtitle/parser_base.dart';

class ParserSMI extends ParserBase {
  @override
  RegExp get regExp => RegExp(
        r'<SYNC Start=(\d+)><P Class=(.*?>)(\r|\n)*((((?!<SYNC|<\/BODY).*)(\r|\n))+)',
        caseSensitive: false,
        multiLine: true,
      );

  @override
  Subtitles getSubtitlesData(String subtitlesContent) {
    subtitlesContent = subtitlesContent.replaceAll(
        RegExp('<font (.*?=)(.*?>)|</font>|<b>|</b>|　|<i>|</i>',
            caseSensitive: false, multiLine: false),
        '');

    final matches = regExp.allMatches(subtitlesContent).toList();
    final subtitleList = <Subtitle>[];
    Subtitle? lastItem;
    for (final regExpMatch in matches) {
      var startTime = Time(
          Duration(milliseconds: int.parse(regExpMatch.group(1).toString())));
      var content = regExpMatch.group(4)!;
      if (lastItem != null) {
        lastItem.endTime.duration = startTime.before;
        lastItem = null;
      }

      if (!content.contains('&nbsp;')) {
        content = content
            .replaceAll(RegExp(r'(\r\n|\r|\n)', caseSensitive: false), '')
            .replaceAll(RegExp(r'(<br>|<\/br>)', caseSensitive: false), ' ')
            .trim();
        content = removeAllHtmlTags(content);

        if (content.isNotEmpty) {
          if (subtitleList.isNotEmpty &&
              content.contains(subtitleList.last.text)) {
            subtitleList.last.text = content;
            lastItem = subtitleList.last;
          } else {
            var endTime = Time(Duration());
            lastItem =
                Subtitle(startTime: startTime, endTime: endTime, text: content);
            subtitleList.add(lastItem);
          }
        }
      }
    }
    // for (var item in subtitleList) {
    //   print(
    //       '${item.startTime.toString()} --> ${item.endTime.toString()} >> ${item.text}');
    // }
    return Subtitles(subtitles: subtitleList);
  }
}
