package com.example.wallpapermagazine;

import android.app.WallpaperManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.wallpapermagazine.databinding.BottomSheetWallpaperOptionsBinding;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;

import java.io.IOException;

public class WallpaperOptionsBottomSheet extends BottomSheetDialogFragment {
    private BottomSheetWallpaperOptionsBinding binding;
    private Bitmap wallpaperBitmap;

    public void setWallpaperBitmap(Bitmap bitmap) {
        this.wallpaperBitmap = bitmap;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = BottomSheetWallpaperOptionsBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        binding.setWallpaperButton.setOnClickListener(v -> {
            // 设置壁纸逻辑
            requireActivity().findViewById(R.id.textview_loading).setVisibility(View.GONE);
            setPhoneWallpaper(wallpaperBitmap, WallpaperManager.FLAG_SYSTEM);
            dismiss();
        });

        binding.setLockscreenButton.setOnClickListener(v -> {
            // 设置锁屏逻辑
            requireActivity().findViewById(R.id.textview_loading).setVisibility(View.GONE);
            setPhoneWallpaper(wallpaperBitmap, WallpaperManager.FLAG_LOCK);
            dismiss();
        });

        binding.setBothButton.setOnClickListener(v -> {
            requireActivity().findViewById(R.id.textview_loading).setVisibility(View.GONE);
            setPhoneWallpaper(wallpaperBitmap, WallpaperManager.FLAG_SYSTEM | WallpaperManager.FLAG_LOCK);
            dismiss();
        });
    }

    private void setPhoneWallpaper(Bitmap bitmap, int which) {
        WallpaperManager wallpaperManager = WallpaperManager.getInstance(requireContext());
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                wallpaperManager.setBitmap(bitmap, null, true, which);
            }
            Toast.makeText(getContext(), "Wallpaper set successfully!", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "Failed to set wallpaper!", Toast.LENGTH_SHORT).show();
        }
    }
}