package com.reactnativenavigation.views.touch;

import android.graphics.Rect;
import android.support.annotation.VisibleForTesting;
import android.view.MotionEvent;
import android.view.ViewGroup;

import com.reactnativenavigation.parse.params.Bool;
import com.reactnativenavigation.parse.params.NullBool;
import com.reactnativenavigation.utils.UiUtils;
import com.reactnativenavigation.viewcontrollers.IReactView;

public class OverlayTouchDelegate {
    private enum TouchLocation {Outside, Inside}
    private final Rect hitRect = new Rect();
    private IReactView reactView;
    private Bool interceptTouchOutside = new NullBool();

    public OverlayTouchDelegate(IReactView reactView) {
        this.reactView = reactView;
    }

    public boolean onInterceptTouchEvent(MotionEvent event) {
        if (interceptTouchOutside instanceof NullBool) return false;
        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                return handleDown(event);
            default:
                reactView.dispatchTouchEventToJs(event);
                return false;

        }
    }

    @VisibleForTesting
    public boolean handleDown(MotionEvent event) {
        TouchLocation location = getTouchLocation(event);
        if (location == TouchLocation.Inside) {
            reactView.dispatchTouchEventToJs(event);
        }
        if (interceptTouchOutside.isTrue()) {
            return location == TouchLocation.Inside;
        }
        return location == TouchLocation.Outside;
    }

    private TouchLocation getTouchLocation(MotionEvent ev) {
        ((ViewGroup) reactView.asView()).getChildAt(0).getHitRect(hitRect);
        return hitRect.contains((int) ev.getRawX(), (int) ev.getRawY() - UiUtils.getStatusBarHeight(reactView.asView().getContext())) ?
                TouchLocation.Inside :
                TouchLocation.Outside;
    }

    public void setInterceptTouchOutside(Bool interceptTouchOutside) {
        this.interceptTouchOutside = interceptTouchOutside;
    }
}

@@ -157,16 +157,42 @@
 nEvent;%0A
+import android.view.View;%0A
 import a
@@ -214,16 +214,16 @@
 wGroup;%0A
-
 %0Aimport 
@@ -655,16 +655,154 @@
 ool();%0A%0A
+    public void setInterceptTouchOutside(Bool interceptTouchOutside) %7B%0A        this.interceptTouchOutside = interceptTouchOutside;%0A    %7D%0A%0A
     publ
@@ -1754,16 +1754,23 @@
         
+getView
 ((ViewGr
@@ -1798,22 +1798,8 @@
 ()).
-getChildAt(0).
 getH
@@ -2045,132 +2045,113 @@
    p
-ublic void setInterceptTouchOutside(Bool interceptTouchOutside) %7B%0A        this.interceptTouchOutside = interceptTouchOutside
+rivate View getView(ViewGroup view) %7B%0A        return view.getChildCount() %3E 0 ? view.getChildAt(0) : view
 ;%0A  

Fix crash when user tapped on screen before initial meaningful render