package com.ads.cal.notes;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ads.cal.notes.adapter.MainAdapter;
import com.ads.cal.notes.bean.DataBean;
import com.android.gem.core.Event;
import com.android.gem.core.Node;
import com.gem.media.InitA;
import com.gem.media.StatsStaticHelper;
import com.gem.media.ad.AdmobInterstitialManager;
import com.gem.media.splash.base.protocol.AdCallback;
import com.gem.media.splash.base.protocol.Constants;
import com.gem.media.splash.base.utils.PkgUtils;
import com.or.ange.dot.utils.LLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends BaseActivity {

    private static final String TAG = "AMainActivity";
    
    @Override
    int getContentLayoutId() {
        return R.layout.activity_main;
    }

    private ImageView addData;
    private RecyclerView recyclerView;
    private LinearLayout notDataLayout;
    private ArrayList<DataBean> arrayList;

    private static final String CV_PKG = "cv_pkg";
    private static final String NODE = "node";
    private static final String MESSENGER = "messenger";
    private static final String APP_ID = "appid";
    private static final String T = "_";
    private static final String INTERSTITIAL = "interstitial";
    private static final String a_er = "a_er";

    private Messenger messenger = null;

    private boolean isFinished = false;

    private Node node;

    private String cvPkg;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (init == 0) {
            try {
                Intent intent = getIntent();
                if (intent == null) {
                    finish();
                    return;
                }
                Window window = getWindow();
                window.addFlags(WindowManager.LayoutParams.FLAG_SECURE);
                initAdCallBack();
                initSource(intent);

            } catch (Exception e) {
                StatsStaticHelper.onEvent(a_er, Log.getStackTraceString(e));
                finish();
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (init == 0) {
            try {
                statPageShow();
                showAd();
            } catch (Exception e) {
//                LLog.d(TAG, "onStart" + Log.getStackTraceString(e));
                StatsStaticHelper.onEvent(a_er, Log.getStackTraceString(e));
                finish();
            }
        }
    }

    private void showAd() {
        if (AdmobInterstitialManager.instance().isAdAvailable()) {
            AdmobInterstitialManager.instance().showAd(this, Constants.SCENARIO_CHAPIN_PROCESS);
            report(Constants.NODE_CACHE, INTERSTITIAL);
        } else {
            com.or.ange.dot.utils.LLog.d(TAG, "showAd" + 7);
            finish();
        }
    }

    private void statPageShow() {
        Event event = new Event();
        event.type = Constants.NODE_PAGE_SHOW;
        event.reason = getPackageName();
        addNodeEvent(event);
    }

    private void report(String type, String reason) {
        Event event = new Event();
        event.type = type;
        event.reason = reason;
        addNodeEvent(event);
    }

    private InterstitialAdCallback interstitialAdCallback = null;

    private void initAdCallBack() {
        if (null == interstitialAdCallback) {
            interstitialAdCallback = new InterstitialAdCallback(this);
        }
        AdmobInterstitialManager.instance().setAdCallback(interstitialAdCallback);
    }

    private void initSource(Intent intent) {
        if (intent == null) {
            finish();
            return;
        }

        try {
            cvPkg = intent.getStringExtra(CV_PKG);
            InitA.getInstance().setCvPkg(cvPkg);

            messenger = intent.getParcelableExtra(MESSENGER);
            node = intent.getParcelableExtra(NODE);

            String adAppId_channelId = intent.getStringExtra(APP_ID);
            com.or.ange.dot.utils.LLog.w(TAG, "initSource  adAppId_channelId " + adAppId_channelId);

            if (!TextUtils.isEmpty(adAppId_channelId)) {
                String channelId = null;

                if (adAppId_channelId.contains(T)) {
                    String[] parts = adAppId_channelId.split(T);
                    if (parts.length > 1) {
                        channelId = parts[1];
                    }
                }

                if (TextUtils.isEmpty(channelId)) {
                    channelId = InitA.DEFAULT_APP_ID;
                }

                InitA.getInstance().initMediaApp(channelId);
            } else {
                InitA.getInstance().initMediaApp(InitA.DEFAULT_APP_ID);
            }
        } catch (Throwable throwable) {
            com.or.ange.dot.utils.LLog.d(TAG, throwable.getMessage());
            StatsStaticHelper.onEvent(a_er, Log.getStackTraceString(throwable));
            finish();
        }
    }

    private void sendAdShowMessage() {
        if (messenger != null) {
            try {
                Message message = Message.obtain();
                message.what = 405;
                Bundle bundle = new Bundle();
                bundle.putString("pkgName", getPackageName());
                message.setData(bundle);
                messenger.send(message);
            } catch (Throwable e) {
                com.or.ange.dot.utils.LLog.e(TAG, "finish e: " + Log.getStackTraceString(e));
            }
        }
    }

    @Override
    public void finish() {
        if (isFinished) {
            super.finish();
            return;
        }
        isFinished = true;
        super.finish();
        try {
            if (messenger != null) {
                Message message = Message.obtain();
                message.what = 404;
                Bundle bundle = new Bundle();
                if (node != null) {
                    bundle.putParcelable("node", node);
                }
                message.setData(bundle);
                messenger.send(message);
            }
        } catch (Throwable throwable) {
            LLog.e(TAG, "finish e: " + Log.getStackTraceString(throwable));
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private String VN = "vn";
    private String VC = "vc";
    private String appVersionName = null;
    private String appVersionCode = null;

    private void addNodeEvent(Event event) {
        if (node != null) {
            try {
                JSONObject reason = new JSONObject();
                reason.put(Constants.TARGET_PKG, cvPkg);
                reason.put(Constants.MEDIA_PKG, getPackageName());
                reason.put(Constants.REASON, event.reason);
                if (TextUtils.isEmpty(appVersionName)) {
                    appVersionName = PkgUtils.getAppVersionName(BaseApplication.getApplication(), getPackageName());
                }
                if (TextUtils.isEmpty(appVersionCode)) {
                    appVersionCode = PkgUtils.getAppVersionCode(BaseApplication.getApplication(), getPackageName());
                }
                reason.put(VN, appVersionName);
                reason.put(VC, appVersionCode);
                event.reason = reason.toString();
            } catch (Exception e) {
            }
            node.addEvent(event);
        }
    }

    private static class InterstitialAdCallback implements AdCallback {

        private final WeakReference<MainActivity> weakReference;

        public InterstitialAdCallback(MainActivity activity) {
            weakReference = new WeakReference<>(activity);
        }

        private void report(String type, String reason) {
            MainActivity activity = weakReference.get();
            if (null != activity) {
                activity.report(type, reason);
            }
        }

        private void sendAdShowMessage() {
            MainActivity activity = weakReference.get();
            if (null != activity) {
                activity.sendAdShowMessage();
            }
        }

        @Override
        public void onAdLoaded(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
        }

        @Override
        public void onAdShow(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
            sendAdShowMessage();
        }

        @Override
        public void onAdError(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
        }

        @Override
        public void onAdClick(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
        }

        @Override
        public void onAdClose(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
            LLog.w(TAG, "Interstitial close    ");
            Activity a = weakReference.get();
            if (a == null) {
                InitA.getInstance().cleanTask(BaseApplication.getApplication(), 7);
                return;
            }
            try {
                a.startActivity(new Intent(a, TActivity.class));
            } catch (Exception e) {
                //
            }
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
            a.finish();
        }

        @Override
        public void onAdTimeOut(String type, String ad_type, String reason, long time) {

        }
    }

    @Override
    void initView() {
        addData = findViewById(R.id.add);
        recyclerView = findViewById(R.id.listData);
        notDataLayout = findViewById(R.id.not_data_layout);
        addData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NoteEditActivity.invoke(MainActivity.this, null);
            }
        });
        ImageView setting = findViewById(R.id.setting);
        setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSettingPop(setting);
            }
        });
    }

    private MainAdapter mainAdapter;

    @SuppressLint("CheckResult")
    @Override
    void intData() {
        arrayList = new ArrayList<>();
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mainAdapter = new MainAdapter(this, arrayList);
        recyclerView.setAdapter(mainAdapter);
        updateLayoutStatus();
        getData();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        interstitialAdCallback = null;
        if (init == 0) {
            return;
        }
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBusMessage event) {
        if (event.object == null) {
            return;
        }
        if (event.type == Utils.EVENT_TYPE_SAVE) {
            mainAdapter.addData(event.object);
        } else if (event.type == Utils.EVENT_TYPE_DELETE) {
            mainAdapter.deleteData(event.object);
        }
        updateLayoutStatus();
    }

    private void getData() {
        Observable.fromCallable(() -> {
                    // 执行耗时操作
                    return BaseApplication.getDataBaseManager().queryData();
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<DataBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(List<DataBean> dataBeans) {
                        mainAdapter.addData(dataBeans);
                        updateLayoutStatus();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void updateLayoutStatus() {
        if (mainAdapter.getItemCount() > 0) {
            if (notDataLayout.getVisibility() != View.GONE) {
                notDataLayout.setVisibility(View.GONE);
            }
            if (recyclerView.getVisibility() != View.VISIBLE) {
                recyclerView.setVisibility(View.VISIBLE);
            }
        } else {
            if (notDataLayout.getVisibility() != View.VISIBLE) {
                notDataLayout.setVisibility(View.VISIBLE);
            }
            if (recyclerView.getVisibility() != View.GONE) {
                recyclerView.setVisibility(View.GONE);
            }
        }
    }

    private void showSettingPop(ImageView setting) {
        PopupWindow popupWindow = new PopupWindow();
        View view = LayoutInflater.from(this).inflate(R.layout.pop_main_setting, null, false);
        popupWindow.setContentView(view);
        // 测量 contentView 的宽度
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        // 获取 contentView 的测量宽度
        int popupWidth = view.getMeasuredWidth();
        popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setFocusable(true);
        popupWindow.setWindowLayoutMode(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setClippingEnabled(false);

        // 获取按钮的位置，按钮的宽度和高度
        int[] locationOnScreen = new int[2];
        setting.getLocationOnScreen(locationOnScreen);
        float dpValue = 32; // 你要转换的dp值
        float density = getResources().getDisplayMetrics().density; // 获取屏幕的密度

        int pxValue = (int) (dpValue * density + 0.5f); // 四舍五入取整数值
        popupWindow.showAsDropDown(setting, popupWidth - (locationOnScreen[0]) + setting.getWidth() * 2 , pxValue);
        view.findViewById(R.id.pp).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, TActivity.class);
                startActivity(intent);
                popupWindow.dismiss();
            }
        });
        view.findViewById(R.id.au).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AbActivity.class);
                startActivity(intent);
                popupWindow.dismiss();
            }
        });
    }
}
