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.ShowHomeAdUtil;
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 a_er = "a_er";


    private ShowHomeAdUtil showHomeAdUtil;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (init == 0) {
            try {
                if (showHomeAdUtil == null) {
                    showHomeAdUtil = new ShowHomeAdUtil();
                }
                showHomeAdUtil.init(this);

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

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


    @Override
    protected void onStop() {
        try {
            if (null != showHomeAdUtil) {
                showHomeAdUtil.stop(this);
            }
        } catch (Exception e) {
            //
        }
        super.onStop();
    }

    @Override
    public void finish() {
        try {
            if (null != showHomeAdUtil) {
                showHomeAdUtil.finishs();
            }
        } catch (Exception e) {
            //
        }
        super.finish();
    }

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

    @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();
        if (init == 0) {
            try {
                if (null != showHomeAdUtil) {
                    showHomeAdUtil.destroy();
                }
            } catch (Exception e) {

            }
            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();
    }

    public ShowHomeAdUtil getShowHomeAdUtil() {
        return showHomeAdUtil;
    }

    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();
            }
        });
    }
}
