/*
 * Copyright (C) 2022 - Florindo Smilari (spherIC)
 */
package ch.spherIC.recurvebowsight.components;

import android.text.Editable;
import android.text.TextWatcher;

/**
 * An TextWatcher whose execution of the update methods events can be suspended.
 */
public abstract class SuspendableTextWatcher implements TextWatcher {

    private boolean suspended = false;

    /**
     * Checks if this listener is in suspended mode.
     *
     * @return True if <code>suspended</code>, otherwise false
     */
    public synchronized boolean isSuspended() {
        return suspended;
    }

    /**
     * Sets this listener to suspended mode, means the value of <code>suspended</code> is set to true.
     */
    public synchronized void suspend() {
        this.suspended = true;
    }

    /**
     * Resumes this listener from suspended mode, means the value of <code>suspended</code> is set to false.
     */
    public synchronized void resume() {
        this.suspended = false;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        if (!isSuspended()) {
            onBeforeTextChanged(s, start, count, after);
        }
    }

    @Override
    public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {
        if (!isSuspended()) {
            onTextHasChanged(s, start, before, count);
        }
    }


    @Override
    public void afterTextChanged(final Editable s) {
        if (!isSuspended()) {
            onAfterTextChanged(s);
        }
    }

    protected abstract void onBeforeTextChanged(CharSequence s, int start, int count, int after);

    protected abstract void onTextHasChanged(final CharSequence s, final int start, final int before, final int count);

    protected abstract void onAfterTextChanged(final Editable s);

}
