package com.webileapps.excalibur;

import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.widget.FrameLayout;

public class ExcaliburWebChromeClient extends WebChromeClient {

    private View mCustomView;
    private WebChromeClient.CustomViewCallback mCustomViewCallback;
    private Window window;
    private final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);


    public ExcaliburWebChromeClient(Window window) {
        this.window = window;
    }

    public void setWindow(Window window) {
        this.window = window;
    }

    @Override
    public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) {
//            onShowCustomView(view, callback);    //To change body of overridden methods use File | Settings | File Templates.
    }

    @Override
    public void onShowCustomView(final View view,CustomViewCallback callback) {
        // if a view already exists then immediately terminate the new one
        if (this.mCustomView != null || this.window == null) {
            callback.onCustomViewHidden();
            return;
        }

        ((FrameLayout)window.getDecorView()).addView(view, COVER_SCREEN_PARAMS);
        ViewGroup.LayoutParams lp = view.getLayoutParams();
        lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        this.mCustomView = view;
        this.mCustomViewCallback = callback;
        new android.os.Handler().postDelayed(new Runnable(){
            @Override
            public void run() {
                View fullScreenView = ((FrameLayout)view).getChildAt(0);
                ViewGroup.LayoutParams lp = fullScreenView.getLayoutParams();
                lp.height = view.getHeight() * 15/16;
                fullScreenView.setLayoutParams(lp);
            }
        }, 100);
    }

    @Override
    public void onHideCustomView() {
        if (this.mCustomView == null || this.window == null) {
            return;
        }
        ((FrameLayout)window.getDecorView()).removeView(this.mCustomView);
        this.mCustomView = null;
        this.mCustomViewCallback.onCustomViewHidden();
        this.mCustomViewCallback = null;
    }
}
