package com.atmob.voiceai.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.method.ScrollingMovementMethod;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class AutoScrollTextView extends androidx.appcompat.widget.AppCompatTextView {


    public AutoScrollTextView(@NonNull Context context) {
        this(context, null);
    }

    public AutoScrollTextView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AutoScrollTextView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setMovementMethod(ScrollingMovementMethod.getInstance());
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        getParent().requestDisallowInterceptTouchEvent(true);
        return super.dispatchTouchEvent(ev);
    }


    public void startScroll() {
        scrollTo(0, 0);
        postScroll();
    }

    public void stopScroll() {
        getHandler().removeCallbacksAndMessages(null);
    }

    private void postScroll() {
        post(() -> {
            int scrollY = getScrollY();
            scrollY += 1;
            scrollTo(0, scrollY);
            if (scrollY >= getLineHeight() * getLineCount() - getHeight()) {
//                scrollTo(0, 0);
                stopScroll();
            }
            postDelayed(this::postScroll, 50);
        });
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        removeCallbacks(this::postScroll);
    }
}
