package io.scanbot.sdk.reactnative.components.common;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import java.util.ArrayList;
import java.util.List;

public class ScanbotComponentFrameLayout extends FrameLayout {

    interface ILayoutChangeListener {
        void onFrameLayoutChanged(int width, int height, int left, int top, int right, int bottom);
    }

    public ScanbotComponentFrameLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ScanbotComponentFrameLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public final Runnable measureAndLayout =
            new Runnable() {
                @Override
                public void run() {
                    measure(
                            MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY),
                            MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY));
                    layout(getLeft(), getTop(), getRight(), getBottom());
                    notifyListeners(getWidth(), getHeight(), getLeft(), getTop(), getRight(), getBottom());
                }
            };

    private final List<ILayoutChangeListener> layoutChangeListeners = new ArrayList<>();

    @Override
    public void requestLayout() {
        super.requestLayout();
        post(measureAndLayout);
    }

    public void addLayoutChangeListener(ILayoutChangeListener listener) {
        layoutChangeListeners.add(listener);
    }

    private void notifyListeners(int width, int height, int left, int top, int right, int bottom) {
        for(ILayoutChangeListener listener : layoutChangeListeners) {
            listener.onFrameLayoutChanged(width, height, left, top, right, bottom);
        }
    }
}