package com.ads.cal.notes;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

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.ads.cal.notes.callback.OnShowAdEndCallBack;
import com.ads.cal.notes.manager.InterstitialAdManager;

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

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 {

    @Override
    int getContentLayoutId() {
        return R.layout.activity_main;
    }

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

    @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();
        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) {
                if (InterstitialAdManager.getInstance().hasCache()) {
                    InterstitialAdManager.getInstance().setOnShowAdCallBack(new OnShowAdEndCallBack() {
                        @Override
                        public void onShowAdComplete() {
                            Intent intent = new Intent(MainActivity.this, TActivity.class);
                            startActivity(intent);
                            popupWindow.dismiss();
                        }

                        @Override
                        public void onShowAdFailed(String errorMsg) {
                            Intent intent = new Intent(MainActivity.this, TActivity.class);
                            startActivity(intent);
                            popupWindow.dismiss();
                        }
                    });
                    InterstitialAdManager.getInstance().showInterstitial(MainActivity.this);
                } else {
                    Intent intent = new Intent(MainActivity.this, TActivity.class);
                    startActivity(intent);
                    popupWindow.dismiss();
                    InterstitialAdManager.getInstance().loadAd();
                }
            }
        });
        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();
            }
        });
    }
}
