package com.gem.media;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.Gravity;
import android.view.WindowManager;

import com.ads.cal.notes.BaseApplication;
import com.android.gem.core.ReportBean;
import com.gem.media.ad.view.NativeAdView;
import com.gem.media.splash.base.protocol.Constants;
import com.gem.media.splash.base.utils.ALog;

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

public class NativeAdWindManager {

    private static final class NativeAdWindManagerHolder {
        private static final NativeAdWindManager NativeAdWindManager = new NativeAdWindManager();
    }

    public static NativeAdWindManager getInstance() {
        return NativeAdWindManager.NativeAdWindManagerHolder.NativeAdWindManager;
    }

    private static final Handler handler = new Handler(Looper.getMainLooper());

    private WindowManager windowManager;

    private WindowManager.LayoutParams layoutParams;
    private NativeAdView mNativeAdView;
    private String adType;

    public void createNativeAdView(String adType) {
        handler.removeCallbacks(runnable);
        handler.removeCallbacks(removeRunnable);
        ALog.d("NativeAdWindManager", "createNativeAdView" +" adType " +adType );
        StatsStaticHelper.onEvent(Constants.N_CREATE);
        this.adType = adType;
        if (!isMainThread()) {
            handler.post(runnable);
        } else {
//            create(context);
            startNActivity();
        }
    }

    private final Runnable runnable = this::startNActivity;

    private final Runnable removeRunnable = this::closeNActivity;

    private void create(Context context) {
        if (context == null) {
            return;
        }
        handler.removeCallbacks(removeRunnable);
        goneNativeAd();
        try {
            PackageManager pm = context.getPackageManager();
            int granted = pm.checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, context.getPackageName());
            if (granted != PackageManager.PERMISSION_GRANTED) {
                StatsStaticHelper.onEvent(Constants.N_WM_NOT_PER);
                ALog.d("NativeAdWindManager", "create window not permission");
                return;
            } else {
                StatsStaticHelper.onEvent(Constants.N_WM_PER);
            }
            if (false) {
                if (windowManager == null) {
                    windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
                }
                if (mNativeAdView == null) {
                    mNativeAdView = new NativeAdView(context);
                    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.flags = (WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                            | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                            | WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                    layoutParams.format = PixelFormat.TRANSLUCENT;
                    layoutParams.gravity = Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL;
                    layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
                    layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
                }
                mNativeAdView.setLayoutParams(layoutParams);
                windowManager.addView(mNativeAdView, layoutParams);
                ALog.d("NativeAdWindManager", "create window end");
            } else {
                ALog.d("NativeAdWindManager", "reload");

            }
        } catch (Exception e) {
            e.printStackTrace();
            ALog.e("NativeAdWindManager", "eee "+e.getMessage());
        }
    }

    public void removeNativeAd() {
        handler.removeCallbacks(removeRunnable);
        if (!isMainThread()) {
            handler.post(removeRunnable);
        } else {
//            goneNativeAd();
            closeNActivity();
        }
    }

    private void goneNativeAd() {
        try {
            if (null != windowManager && mNativeAdView != null) {
                windowManager.removeView(mNativeAdView);
                mNativeAdView.removeAllViews();
                mNativeAdView = null;
                StatsStaticHelper.onEvent(Constants.N_REMOVE);
            }
        } catch (Exception e) {
            ALog.e("NativeAdWindManager", "eee "+e.getMessage());
        } finally {
        }

    }


    private void startNActivity() {
        ALog.e("NativeAdWindManager", "startNActivity adType ");
        boolean isAppBackground = InitA.getInstance().isAppBackground();
        if (isAppBackground) {
            ALog.e("NativeAdWindManager", "1   adType "+adType);
            Intent intent = new Intent(BaseApplication.getApplication(), NActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP);
            intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
            intent.putExtra("adType", adType);
            BaseApplication.getApplication().startActivity(intent);
        } else {
            ALog.e("NativeAdWindManager", "2  adType "+adType);
            Messenger messenger = InitA.getInstance().getMessenger();
            if (null == messenger) {
                return;
            }
            try {
                Map<String, String> map = new HashMap<>();
                map.put(Constants.MEDIA_PKG, BaseApplication.getApplication().getPackageName());

                ReportBean reportBean = new ReportBean();
                reportBean.setType("reshow");
                if (!map.isEmpty()) {
                    reportBean.setData(map);
                }
                Message message = Message.obtain();
                message.what = 5002;
                Bundle bundle = new Bundle();
                bundle.putParcelable("reportBean", reportBean);
                message.setData(bundle);
                messenger.send(message);
            } catch (RemoteException e) {
            }
        }
    }

    private void closeNActivity() {
    }

    private boolean isMainThread() {
        return Looper.getMainLooper().getThread() == Thread.currentThread();
    }

}
