package com.key.vibekeyboard.Dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.key.vibekeyboard.AppApplication;
import com.key.vibekeyboard.R;
import com.key.vibekeyboard.Utils.Mytool;
import com.key.vibekeyboard.databinding.DialogPermissionBinding;

public class PermissionRequestDialog extends DialogFragment {

    private DialogPermissionBinding binding;
    private InputMethodManager methodManager;
    private ContentObserver inputMethodObserver; // 用于监听输入法变化

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

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

    @Override
    public void onResume() {
        super.onResume();
        Dialog dialog = getDialog();
        setCancelable(true);
        if (dialog != null && dialog.getWindow() != null) {
            Window window = dialog.getWindow();
            window.setLayout((int) (getResources().getDisplayMetrics().widthPixels * 0.9), WindowManager.LayoutParams.WRAP_CONTENT);
        }

        update();
    }

    public void init() {
        methodManager = (InputMethodManager) AppApplication.instance.getSystemService(Context.INPUT_METHOD_SERVICE);

        Glide.with(requireContext())
                .load(R.mipmap.ic_launcher_foreground)
                .transform(new RoundedCorners(16))
                .into(binding.imageView);

        binding.firstIconTextLayout.setOnClickListener(v -> {
            Intent intent = new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS);
            startActivity(intent);
        });

        binding.secondIconTextLayout.setOnClickListener(v -> {
            methodManager.showInputMethodPicker();
        });

        binding.imageView.setOnClickListener(v -> dismiss());

        // 注册ContentObserver监听输入法变化
        inputMethodObserver = new ContentObserver(new Handler(Looper.getMainLooper())) {
            @Override
            public void onChange(boolean selfChange) {
                super.onChange(selfChange);
                if (Mytool.isStep1() && Mytool.isStep2()) {
                    dismiss(); // 条件满足，关闭对话框
                }
            }
        };

        // 注册观察输入法变化
        requireContext().getContentResolver().registerContentObserver(
                Settings.Secure.getUriFor(Settings.Secure.DEFAULT_INPUT_METHOD),
                false,
                inputMethodObserver
        );
    }

    public void update() {
        if (Mytool.isStep1()) {
            binding.firstIconTextLayout.setSelected(Mytool.isStep1());
            binding.firstIconTextLayout.setClickable(false);
        }
        if (Mytool.isStep2()) {
            binding.secondIconTextLayout.setSelected(Mytool.isStep2());
            binding.secondIconTextLayout.setClickable(false);
        }

        if (Mytool.isStep1() && Mytool.isStep2()) {
            dismiss();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (inputMethodObserver != null) {
            requireContext().getContentResolver().unregisterContentObserver(inputMethodObserver);
        }
        binding = null;
    }
}
