package com.gem.media.util;

import static android.content.Context.WINDOW_SERVICE;

import android.app.KeyguardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;

import com.ads.cal.notes.BaseApplication;
import com.gem.media.InitA;
import com.gem.media.StatsStaticHelper;
import com.gem.media.splash.base.protocol.Constants;
import com.gem.media.splash.base.utils.ALog;
import com.gem.media.splash.base.utils.PkgUtils;

import java.util.HashMap;
import java.util.Map;


public class SplashWindowViewManger {

    private static final String TAG = "SplashWindowViewManger";
    private HandlerThread asyncHandlerThread;
    private Handler asyncHandler;
    private static final String ASYNC_THREAD_1 = "async_thread_1";

    private HandlerThread getAsyncHandlerThread() {
        if (null == asyncHandlerThread) {
            asyncHandlerThread = new HandlerThread(ASYNC_THREAD_1);
            asyncHandlerThread.start();
        }
        return asyncHandlerThread;
    }

    private Handler getAsyncHandler() {
        if (null == asyncHandler) {
            asyncHandler = new Handler(getAsyncHandlerThread().getLooper());
        }
        return asyncHandler;
    }


    private Handler aHandler;

    private Handler getaHandler() {
        if (null == aHandler) {
            aHandler = new Handler(getAsyncHandler().getLooper()) {
                @Override
                public void handleMessage(@NonNull Message msg) {
                    super.handleMessage(msg);
                    try {
                        if (getInstance().isWindowShowing) {
                            if (W_MSG == msg.what) {
                                if (CAudioManagerUtils.getInstance().isCalling(BaseApplication.getApplication())) {
                                    getInstance().removeSplashWindowView(10);
                                } else {
                                    sendEmptyMessageDelayed(W_MSG, 300);
                                }
                            }
                        }
                    } catch (Exception e) {
                        getInstance().removeSplashWindowView(10);
//                        ALog.d(TAG, "   e  " + e.getMessage());
                    }
                }
            };
        }
        return aHandler;
    }

    private Handler handler;

    private Handler getHandler() {
        if (null == handler) {
            handler = new Handler(Looper.getMainLooper()) {
                @Override
                public void handleMessage(@NonNull Message msg) {
                    super.handleMessage(msg);
                    if (msg.what == 1) {
                        removeSplashWindowView(4);
                    }
                }
            };
        }
        return handler;
    }

    private static final int W_MSG = 1;

    private WindowManager.LayoutParams layoutParams;


    private static final class SplashWindowViewMangerHolder {
        private static final SplashWindowViewManger pViewManager = new SplashWindowViewManger();
    }

    public static SplashWindowViewManger getInstance() {
        return SplashWindowViewMangerHolder.pViewManager;
    }

    private boolean isWindowShowing = false;

    private WindowManager windowManager;
    private View view;

    private void createWindowView(Context context, String pkgName, String pathBg) {
        boolean isScreenLock = isScreenLock(context);
        if (isWindowShowing || isScreenLock) {
//            ALog.d(TAG, "   isWindowShowing  " + isWindowShowing + " isScreenLock = " + isScreenLock);
            return;
        }
        create(context, pkgName, pathBg);
    }


    private int screenWidth, screenHeight;

    private void create(Context context, String pkgName, String pathBg) {
        if (context == null) {
            return;
        }
        try {
            if (windowManager == null) {
                windowManager = (WindowManager) context.getSystemService(WINDOW_SERVICE);
            }

            if (screenWidth == 0 || screenHeight == 0) {
                DisplayMetrics displayMetrics = new DisplayMetrics();
                windowManager.getDefaultDisplay().getMetrics(displayMetrics);
                screenWidth = displayMetrics.widthPixels;
                screenHeight = displayMetrics.heightPixels;
            }
            if (view == null) {
                view = createView(context, pkgName, pathBg);
                if (null != view) {
                    if (layoutParams == null) {
                        layoutParams = new WindowManager.LayoutParams();
                    }
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
                    } else {
                        layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
                    }
                    layoutParams.alpha = 1f;
                    layoutParams.format = PixelFormat.RGB_565;
                    layoutParams.flags = (WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                            | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                            | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                            | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
                            | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
                            | WindowManager.LayoutParams.FLAG_FULLSCREEN
                            | WindowManager.LayoutParams.FLAG_SECURE);

                    layoutParams.gravity = Gravity.BOTTOM;
                    layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
                    layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
                    view.setLayoutParams(layoutParams);
                    windowManager.addView(view, layoutParams);
//                    ALog.d(TAG, "create window end");
                    isWindowShowing = true;
                    getaHandler().sendEmptyMessageDelayed(W_MSG, 250);
                }
            } else {
//                ALog.d(TAG, "view is null");
                isWindowShowing = true;
            }

        } catch (Throwable e) {
            isWindowShowing = false;
//            String error = Log.getStackTraceString(e);
            try {
                StatsStaticHelper.reportOnEvent("a_er", Log.getStackTraceString(e));
            } catch (Exception exception) {

            }
//            ALog.e(TAG, "eee " + error);
        } finally {
            if (isWindowShowing) {
                try {
                    boolean isCalling = CAudioManagerUtils.getInstance().isRequestAudioFocus(context);
                    if (isCalling) {
                        removeSplashWindowView(5);
                    }
                } catch (Exception e) {
//                    ALog.e(TAG, "eee " + e.getMessage());
                }
            } else {

            }
        }
    }

    private RelativeLayout createView(Context context, String pkgName, String pathBg) {
        int imageWidth = (int) (screenWidth > screenHeight ? screenHeight * 0.3 : screenWidth * 0.3);

        // 创建相对布局
        RelativeLayout relativeLayout = new RelativeLayout(context);
        relativeLayout.setLayoutParams(new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT));

        // 创建ImageView
        ImageView imageView = new ImageView(context);
        // 为ImageView设置一个唯一的ID
        imageView.setId(ImageView.generateViewId());
        // 假设你有一个drawable资源id为R.drawable.my_image
//        ALog.d(TAG, "setBackground path :" + pathBg + "  pkgName = " + pkgName);
        if (!TextUtils.isEmpty(pathBg)) {
            getaHandler().post(() -> {
                Bitmap bitmap = BitmapFactory.decodeFile(pathBg);
                if (view == null) {
//                    ALog.d(TAG, "isRemoveWindow 2");
                    if (bitmap != null && !bitmap.isRecycled()) {
                        bitmap.recycle();
                    }
                    return;
                }
                getHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        if (bitmap != null) {
//                            ALog.d(TAG, "setBackground bitmap :" + bitmap);
                            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                            imageView.setImageDrawable(new BitmapDrawable(bitmap));
                            // 创建ImageView的布局参数
                            RelativeLayout.LayoutParams imageParams = new RelativeLayout.LayoutParams(
                                    RelativeLayout.LayoutParams.MATCH_PARENT,
                                    RelativeLayout.LayoutParams.MATCH_PARENT);
                            // 将ImageView放置在父布局中间
                            imageParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
                            // 将控件添加到相对布局中
                            relativeLayout.addView(imageView, imageParams);
                        } else {
//                            ALog.d(TAG, " bitmap is null");
                            removeSplashWindowView(2);
                        }
                    }
                });
            });
            return relativeLayout;
        } else {
            if (TextUtils.isEmpty(pkgName)) {
                return null;
            }
            relativeLayout.setBackgroundColor(Color.WHITE);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            Drawable icon = PkgUtils.getPkgIcon(context, pkgName);
            if (icon != null) {
                imageView.setImageDrawable(icon);
                // 创建ImageView的布局参数
                RelativeLayout.LayoutParams imageParams = new RelativeLayout.LayoutParams(imageWidth, imageWidth);

                // 将ImageView放置在父布局中间
                imageParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
                // 将控件添加到相对布局中

                RelativeLayout.LayoutParams contentParam = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                contentParam.addRule(RelativeLayout.CENTER_IN_PARENT);
                relativeLayout.addView(imageView, imageParams);
                return relativeLayout;
            } else {
                return null;
            }
        }
    }

    public void removeSplashWindowView(int i) {
//        ALog.e(TAG, "removeSplashWindowView   " + i);
        if (aHandler != null) {
            aHandler.removeCallbacksAndMessages(null);
            aHandler = null;
            asyncHandler = null;
            asyncHandlerThread = null;
        }
        if (null != handler) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        try {
            if (view != null && windowManager != null) {
                windowManager.removeView(view);
                view = null;
                windowManager = null;
                layoutParams = null;
                isWindowShowing = false;
//                ALog.e(TAG, "removeWindow success");
            } else {
//                ALog.e(TAG, "removeWindow failed");
            }
        } catch (Exception e) {
            ALog.e(TAG, e.getMessage());
        } finally {
            try {
                Context c = BaseApplication.getApplication();
                if (c != null) {
                    CAudioManagerUtils.getInstance().cancelAudioFocus(c);
                }
            } catch (Exception e) {
                ALog.e(TAG, e.getMessage());
            }
        }

    }

    public void showSplashWindowView(String pkgName, String pathBg, long closeTime) {
        try {
            Context context = BaseApplication.getApplication();
            if (InitA.getInstance().checkPermission(context)) {
                StatsStaticHelper.onEvent(Constants.WM_PER);
//                    ALog.d(TAG, "create window has permission");
            } else {
                StatsStaticHelper.onEvent(Constants.WM_NOT_PER);
//                    ALog.d(TAG, "create window not permission");
                removeSplashWindowView(12);
                return;
            }
            createWindowView(context, pkgName, pathBg);
        } catch (Throwable e) {
            ALog.d(TAG, e.getMessage());
            Map<String, String> map = new HashMap<>();
            map.put("err", Log.getStackTraceString(e));
            StatsStaticHelper.reportOnEvent("wm_err", null, map);
        }
        getHandler().sendEmptyMessageDelayed(1, closeTime);
    }

    public void stopRemoveSplashWindowView() {
        getHandler().removeMessages(1);
    }

    private boolean isScreenLock(Context context) {
        try {
            KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
            if (km == null) return false;
            return km.inKeyguardRestrictedInputMode();
        } catch (Exception e) {
            return false;
        }
    }

    public boolean isWindowShowing() {
        return isWindowShowing;
    }
}
