package com.atmob.elec_asst.utils;

import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;


public class SpannableUtil {


    public static void getAgreementSpannableStringBuilder(TextView targetView, String allTxt, String[] targetTxt, @ColorInt int color, boolean isLine, View.OnClickListener... clickListener) {
        if (clickListener.length > 0)
            targetView.setMovementMethod(LinkMovementMethod.getInstance());
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(allTxt);
        int[] targetTextStart = new int[targetTxt.length];
        for (int i = 0; i < targetTxt.length; i++) {
            targetTextStart[i] = allTxt.indexOf(targetTxt[i]);
        }

        for (int i = 0; i < targetTxt.length; i++) {
            int finalI = i;
            ClickableSpan targetSpan = new ClickableSpan() {
                @Override
                public void onClick(@NonNull View widget) {
                    if (finalI < clickListener.length && clickListener[finalI] != null) {
                        clickListener[finalI].onClick(widget);
                    }
                }

                @Override
                public void updateDrawState(@NonNull TextPaint ds) {
                    ds.setColor(color);
                    ds.setUnderlineText(isLine);
                }
            };
            if (targetTextStart[i] < 0) {
                continue;
            }
            spannableStringBuilder.setSpan(targetSpan, targetTextStart[i],
                    targetTextStart[i] + targetTxt[i].length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        }
        targetView.setText(spannableStringBuilder);
    }
}
