package com.indigitall.cordova.inapp;

import android.content.Context;
import android.os.CountDownTimer;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;

import com.indigitall.android.commons.utils.Log;
import com.indigitall.android.inapp.Utils.InAppUtils;
import com.indigitall.android.inapp.Utils.PopUpUtils;
import com.indigitall.android.inapp.callbacks.ShowInAppCallback;
import com.indigitall.android.inapp.models.InApp;
import com.indigitall.android.inapp.models.InAppPopUp;
import com.indigitall.android.inapp.R;
import com.indigitall.cordova.inapp.callbacks.ShowCDVInAppCallback;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

public class CDVInAppPopUp  {
    private static final String TAG = "[IND]InAppPopUp";
    private static Log log = null;
    PopupWindow popupWindow;

    public CDVInAppPopUp(
            Context context,
            String html,
            View view,
            InApp inApp,
            @Nullable ImageButton closeIcon,
            boolean closeIconDisabled,
            @Nullable ShowCDVInAppCallback showInAppCallback) {
        final int showTime = inApp.getProperties().getShowTime();
        draw(context,html,view, inApp, closeIcon, closeIconDisabled, showInAppCallback);
        if (showTime != 0) {
            CountDownTimer count = new CountDownTimer(showTime,1000) {
                @Override
                public void onTick(long millisUntilFinished) { }

                @Override
                public void onFinish() {
                    if (showInAppCallback != null) showInAppCallback.onShowTimeFinished(inApp.getSchema().getCode(), null, showTime);
                    popupWindow.dismiss();
                }
            };
            count.start();
        }
    }

    public void draw(
            Context context,
            String html,
            View view,
            InApp inApp,
            @Nullable ImageButton closeIcon,
            boolean closeIconDisabled,
            @Nullable ShowCDVInAppCallback show) {
        log = new Log(TAG,context);
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout = layoutInflater.inflate(R.layout.webview_popup, null, false);
        final WebView popUp = layout.findViewById(R.id.inAppPopUp);
        ImageButton close = new ImageButton(context);
        ImageButton buttonClose = layout.findViewById(R.id.imageView);
        CardView cardView = layout.findViewById(R.id.layoutWebView);
        RelativeLayout webViewLayout = layout.findViewById(R.id.webViewLayout);
        popupWindow = new PopupWindow(cardView,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        if (inApp.getProperties() != null &&
                inApp.getProperties().getLayout() != null &&
                inApp.getProperties().getLayout().getBorderRadius() != null) {
            int borderRadius = Integer.parseInt(inApp.getProperties().getLayout().getBorderRadius());
            float scale = context.getResources().getDisplayMetrics().density;
            float dpAsPixels = borderRadius*scale + 0.5f;
            cardView.setRadius(dpAsPixels);
        }

        try {
            if (!closeIconDisabled) {
                if (closeIcon != null) {
                    close = closeIcon;
                    if (close.getLayoutParams() == null) {
                        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                        params.addRule(RelativeLayout.ALIGN_PARENT_END);
                        close.setLayoutParams(params);
                    }
                    if (close.getParent() != null){
                        ((ViewGroup)close.getParent()).removeView(close);
                    }
                    buttonClose.setVisibility(View.GONE);
                    webViewLayout.addView(close);

                } else {
                    close = buttonClose;
                    buttonClose.setVisibility(View.VISIBLE);
                }
                close.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (inApp.getProperties().getDismissForever()) {
                            PopUpUtils.addNewInAppToDismissForever(context, inApp);
                        }
                        if (show != null) show.didClosed();
                        popupWindow.dismiss();
                    }
                });
            }

            if (show != null) show.onSuccess(inApp);

            float density = context.getResources().getDisplayMetrics().density;
            float width = PopUpUtils.changeToDP(context, inApp.getSchema().getWidth()*density);
            float height = PopUpUtils.changeToDP(context,inApp.getSchema().getHeight()*density);
            double aspectRadio = PopUpUtils.scalePopUp(width, height);
            popupWindow.setWidth((int)(width*aspectRadio));
            popupWindow.setHeight((int)(height*aspectRadio));

            new Thread(new Runnable() {
                @Override
                public void run() {
                    String finalHtml = "";
                    URL htmlURL = null;
                    try {
                        htmlURL = new URL(html);

                        BufferedReader in = new BufferedReader(
                                new InputStreamReader(
                                        htmlURL.openStream()));

                        String inputLine;
                        while ((inputLine = in.readLine()) != null)
                            finalHtml = finalHtml.concat(inputLine);

                        in.close();

                        String htmlScaleOriginal = "width:"+ inApp.getSchema().getWidth()+"px;height:"+inApp.getSchema().getHeight()+"px";
                        String htmlScaleChanges = "width:100%;height:100%";
                        String htmlChanged = finalHtml.replace(htmlScaleOriginal, htmlScaleChanges).replace("<!DOCTYPE html>","");
                        CDVInAppIndigitall.drawInApp(context, inApp, popUp, htmlChanged, popupWindow, show);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }).start();

            popupWindow.setContentView(layout);
            popupWindow.setFocusable(true);
            popupWindow.setOutsideTouchable(true);

            darkBackground(context, view);

            if (show != null) show.onLoad(inApp.getSchema().getCode(), popUp, popupWindow);
        }catch (Exception ex){
            if (show != null) show.onFail(inApp.getSchema().getCode(), popUp, ex.getMessage());
        }

    }
    private void darkBackground(Context context, View view){
        if (popupWindow != null) {
            popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);

            if (view != null && popupWindow.getContentView().getParent() != null) {
                View container = (View) popupWindow.getContentView().getParent();

                WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
                WindowManager.LayoutParams p = (WindowManager.LayoutParams) container.getLayoutParams();

                p.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
                //dark level
                p.dimAmount = 0.5f;
                wm.updateViewLayout(container, p);
            }
        }
    }

}
