package com.wall.dream.wallpapers.View;

import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;

import com.wall.dream.wallpapers.databinding.View1SettingsBinding;

public class ViewSettings extends Fragment {

    private View1SettingsBinding vb;
    private RateUsDialogHelper rateUsDialogHelper;
    private boolean isDialogShowing = false;

    public ViewSettings() {
    }

    public static ViewSettings newInstance() {
        return new ViewSettings();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        vb = View1SettingsBinding.inflate(inflater, container, false);
        initViews();
        return vb.getRoot();
    }

    private void initViews() {
        // 设置版本号 - 使用后台线程避免阻塞UI
        new Thread(() -> {
            try {
                String versionName = requireContext().getPackageManager()
                        .getPackageInfo(requireContext().getPackageName(), 0).versionName;
                new Handler(Looper.getMainLooper()).post(() -> {
                    if (vb != null && vb.tvVersion != null) {
                        vb.tvVersion.setText(versionName);
                    }
                });
            } catch (PackageManager.NameNotFoundException e) {
                new Handler(Looper.getMainLooper()).post(() -> {
                    if (vb != null && vb.tvVersion != null) {
                        vb.tvVersion.setText("1.1");
                    }
                });
            }
        }).start();

        // Rate Us 点击事件 - 使用轻量Dialog，添加防抖处理
        vb.layoutRate.setOnClickListener(v -> {
            if (isDialogShowing || getContext() == null) {
                return;
            }
            isDialogShowing = true;
            
            try {
                if (rateUsDialogHelper == null) {
                    rateUsDialogHelper = new RateUsDialogHelper();
                }
                rateUsDialogHelper.show(requireContext());
            } catch (Exception e) {
                // 忽略异常，避免崩溃
                e.printStackTrace();
            } finally {
                // 重置标志，允许再次点击
                new Handler(Looper.getMainLooper()).postDelayed(() -> {
                    isDialogShowing = false;
                }, 300);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (rateUsDialogHelper != null) {
            rateUsDialogHelper.cleanup();
            rateUsDialogHelper = null;
        }
        vb = null;
    }
}








