package com.atmob.voiceai.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
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 {

    private static final Handler MAIN_HANDLER = new Handler(Looper.getMainLooper());
    private Runnable autoScrollRunnable;


    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());
        autoScrollRunnable = () -> {
            int scrollY = getScrollY();
            if (scrollY < getLineHeight() * getLineCount() - getHeight()) {
                scrollY += 1;
                scrollTo(0, scrollY);
            }
            MAIN_HANDLER.postDelayed(autoScrollRunnable, 50);
        };
    }


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


    public void startScroll() {
        scrollTo(0, 0);
        MAIN_HANDLER.postDelayed(autoScrollRunnable, 3000);
    }

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


    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        stopScroll();
    }
}
