package com.example.tyre.maintenance.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.databinding.DataBindingUtil;

import com.example.tyre.R;
import com.example.tyre.databinding.DialogTipResultBinding;


/**
 * 写入结果弹窗（2秒自动关闭+手动关闭）
 */
public class TipResultDialog extends Dialog {
    private final DialogTipResultBinding binding;
    private CountDownTimer countDownTimer;
    private final Activity activity;

    public TipResultDialog(Context context,Activity activity) {
        super(context, R.style.MyMiddleDialogStyle);
        this.activity = activity;
        binding =DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.dialog_tip_result, null, false);
        binding.dialogConfirm.setOnClickListener(view -> dismiss());
        setContentView(binding.getRoot());
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initDialogStyle();
        startCountDown();
    }

    /**
     * 设置弹窗样式（匹配原型：大圆角、居中、占屏比例）
     */
    private void initDialogStyle() {
        Window window = getWindow();
        if (window != null) {
            window.setGravity(Gravity.CENTER);
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = (int) (getContext().getResources().getDisplayMetrics().widthPixels * 0.9);
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            window.setAttributes(params);
            window.setBackgroundDrawableResource(android.R.color.transparent);

        }
        // 点击外部不关闭
        setCanceledOnTouchOutside(false);
    }




    /**
     * 启动2秒倒计时（自动关闭）
     */
    private void startCountDown() {
        countDownTimer = new CountDownTimer(500, 500) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {

                dismiss();
                activity.finish();
            }
        };
    }

    public void show(boolean state, String stateText, String info, boolean closeType) {
        super.show();
        binding.dialogState.setVisibility(state ? View.VISIBLE : View.GONE);
        binding.dialogStateText.setText(stateText);
        binding.dialogTip.setText(info);
        if (closeType) {
            countDownTimer.start();
        }


    }



    @Override
    public void dismiss() {
        super.dismiss();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }

    }
}