import 'package:flutter/material.dart';
import 'package:tangheem/classes/colors.dart';
import 'package:tangheem/models/aya_tangheem_type_mapped.dart';

class TextHighLightLengthWidget extends StatelessWidget {
  final String text;
  final TextAlign textAlign;
  int startIndex;
  int endIndex;
  final String highlightAyaNos;
  final String highlightAya;
  final List<AyahTextList> ayahTextList;
  final double fontSize;
  final Color highLightColor;

  TextHighLightLengthWidget({
    Key key,
    this.text,
    this.textAlign = TextAlign.center,
    this.startIndex,
    this.endIndex,
    this.highlightAyaNos = "",
    this.highlightAya = "",
    this.ayahTextList,
    this.fontSize = 18,
    this.highLightColor = ColorConsts.secondaryOrange,
  }) : super(key: key);

  TextStyle textStyle = TextStyle(
    fontFamily: "UthmanicHafs",
    fontSize: 18,
    color: ColorConsts.primaryBlue,
    fontWeight: FontWeight.bold,
  );

  @override
  Widget build(BuildContext context) {
    List<TextSpan> _spans = [];

    // if (startIndex > endIndex) {
    //   endIndex = endIndex + startIndex;
    // }

    int actualStartIndex = 0;
    if (highlightAyaNos.isNotEmpty)
      for (int i = 0; i < ayahTextList.length; i++) {
        var eachAyah = ayahTextList[i];

        var abList = highlightAyaNos.split(",").toList();
        if (!(abList.any((e) => e == eachAyah.ayahNo.toString()))) {
          //print("e:$e");
          //print("eachAyah.ayahNo:${eachAyah.ayahNo}");
          actualStartIndex += eachAyah.ayahText.length;
          //print("actualStartIndex:$actualStartIndex");
        } else {
          break;
        }
      }
    // print("startIndex:$startIndex");
    if (startIndex < 0) {
      startIndex = 0;
    }
    if (actualStartIndex != 0) {
      startIndex++;
      startIndex = actualStartIndex + startIndex;
    }
    endIndex = (highlightAya.length) + startIndex;
    // print("startIndexAf:$startIndex");
    String beforeText = text.substring(0, startIndex);
    //print("beforeText:$beforeText");
    // print("endIndex:$endIndex");
    //print("text:${text.length}");
    String highLightText = text.substring(startIndex, endIndex);
    // print("highLightText:$highLightText");
    // print("highLightText:${highLightText.length}");

    String afterText = text.substring(endIndex, text.length);
    // print("afterText:$afterText");
    _spans.add(_normalText(beforeText));
    _spans.add(_highlightText(highLightText));
    _spans.add(_normalText(afterText));

    return _richText(TextSpan(children: _spans));
  }

  TextSpan _normalText(String text) {
    return TextSpan(
      text: text,
      style: textStyle.copyWith(fontSize: fontSize),
    );
  }

  TextSpan _highlightText(String text) {
    return TextSpan(
      text: text,
      style: textStyle.copyWith(color: highLightColor, fontSize: fontSize),
    );
  }

  RichText _richText(TextSpan text) {
    return RichText(key: key, text: text, textAlign: textAlign);
  }
}