package com.idle.wall.idleactivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import com.idle.wall.IdleApp;
import com.idle.wall.R;
import com.idle.wall.ad.AdsInsUtil;
import com.idle.wall.ad.LoadListener;
import com.idle.wall.ad.ShowListener;
import com.idle.wall.databinding.ActivityIdleLikeBinding;
import com.idle.wall.idleadapter.OnItemclick;
import com.idle.wall.idleadapter.OnLikelist;
import com.idle.wall.idlebean.IdleData;
import com.idle.wall.idleitem.ItemIdleLike;
import com.idle.wall.idletool.Comutils;
import com.idle.wall.idletool.Itemhelper;
import com.idle.wall.idletool.ObectManager;
import com.tradplus.ads.base.bean.TPAdInfo;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;
import java.util.WeakHashMap;

import io.objectbox.reactive.DataSubscription;

public class IdleLikeActivity extends BaseActivity implements OnItemclick {

    private ActivityIdleLikeBinding vb;
    private DataSubscription dataSubscription;
    private ItemIdleLike itemLike;

    // 弱引用监听，避免内存泄漏
    private static class LikeListListener implements OnLikelist {
        private final WeakHashMap<IdleLikeActivity, Object> activityRef;

        public LikeListListener(IdleLikeActivity activity) {
            activityRef = new WeakHashMap<>();
            activityRef.put(activity, null);
        }

        @Override
        public void onLikeList(List<IdleData> dataList) {
            IdleLikeActivity activity = activityRef.keySet().iterator().next();
            if (activity == null || activity.isFinishing() || activity.isDestroyed()) {
                return;
            }
            activity.updateListUi(dataList);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Comutils.initFull(this, false);
        vb = ActivityIdleLikeBinding.inflate(getLayoutInflater());
        setContentView(vb.getRoot());

        initTitleBar();
        initList();
        initNoDataBtn();
    }
    private void initTitleBar() {
        if (vb == null) return;

        vb.tvPageTitle.setText(getString(R.string.like_page_title));
        vb.ivBack.setOnClickListener(v -> {
           onInterceptBackPressed();
        });
    }

    private void initNoDataBtn() {
        if (vb == null) return;

        vb.tvGoCollect.setOnClickListener(v -> {
            Intent intent = new Intent(IdleLikeActivity.this, IdleMainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            intent.putExtra("KEY_SWITCH_TO_HOME_TAB", true);
            startActivity(intent);
            Toast.makeText(this, R.string.go_collect_tip, Toast.LENGTH_SHORT).show();
            finish();
        });
    }

    private void initList() {
        itemLike = new ItemIdleLike(this);
        itemLike.setInfoWallpaperListener(this);
        int spanCount = 2;
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, spanCount);
        vb.listRecycler.setLayoutManager(gridLayoutManager);
        vb.listRecycler.addItemDecoration(new Itemhelper(10, 10, 15));
        vb.listRecycler.setAdapter(itemLike);
        vb.listRecycler.setItemAnimator(null);
        LikeListListener listener = new LikeListListener(this);
        dataSubscription = ObectManager.setLikeDataListener(listener);
    }
    private void updateListUi(List<IdleData> dataList) {
        if (vb == null) return;

        if (dataList == null || dataList.isEmpty()) {
            vb.layoutNoData.setVisibility(View.VISIBLE);
            vb.listRecycler.setVisibility(View.GONE);
            vb.tvTitle.setText(getString(R.string.no_like_data));
        } else {
            vb.layoutNoData.setVisibility(View.GONE);
            vb.listRecycler.setVisibility(View.VISIBLE);
            vb.tvTitle.setText("");
            itemLike.setDataInfo(dataList);
        }
    }
    @Override
    public void onItemClickAction(IdleData info) {
        if (info == null) return;
        Intent intent = new Intent(this, IdleWallActivity.class);
        intent.putExtra(Comutils.key_info, info);
        startActivity(intent);
    }
    @Override
    protected void onPause() {
        super.onPause();
        if (vb != null && vb.listRecycler != null) {
            vb.listRecycler.stopScroll();
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dataSubscription != null) {
            dataSubscription.cancel();
            dataSubscription = null;
        }
        vb = null;
    }

    public static void startLikeActivity(IdleMainActivity context) {
        if (context == null) return;
        Intent intent = new Intent(context, IdleLikeActivity.class);
        context.startActivity(intent);
    }



    @Override
    protected boolean shouldInterceptBackPress() {
        return true;
    }

    @Override
    protected void onInterceptBackPressed() {
        AdsInsUtil.INSTANCE.showAd(this, AdsInsUtil.Placement.TOP_ON_AD_TOW, new ShowListener() {
            @Override
            public void onAdShown(@Nullable TPAdInfo ad) {
                loadAd();
            }

            @Override
            public void onAdClosed() {
                loadAd();
            }
        });
        if (getBackPressedCallback() != null) {
            getBackPressedCallback().setEnabled(false);
        }
        getOnBackPressedDispatcher().onBackPressed();
    }

    private void loadAd(){
        AdsInsUtil.INSTANCE.loadAd(this, AdsInsUtil.Placement.TOP_ON_AD_TOW, new LoadListener() {
            @Override
            public void loadFailed(@NotNull String error) {

            }
        });
    }
}