package com.tofly.latte_core.utils;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import androidx.appcompat.app.AppCompatDialog;

import com.tofly.latte_core.R;
import com.wang.avi.AVLoadingIndicatorView;

/**
 * 加载工具类
 */
public class LoaderUtils {

    private AppCompatDialog mLoadingDialog;

    private Context mContext;

    private static class Holder {
        private static final LoaderUtils LOADER_UTILS = new LoaderUtils();
    }

    public static LoaderUtils getInstance() {
        return Holder.LOADER_UTILS;
    }

    public void showDialog(Context context) {
        mContext = context;

        View view = LayoutInflater.from(context).inflate(R.layout.item_loader_dialog, null);
        final AVLoadingIndicatorView avLoadingIndicatorView = view.findViewById(R.id.av_loader_dialog);
        avLoadingIndicatorView.setIndicator(LoaderStyle.BallClipRotatePulseIndicator.name());
        mLoadingDialog = new AppCompatDialog(context, R.style.dialog);
        mLoadingDialog.setCancelable(false);
        mLoadingDialog.setContentView(view, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));

        try {
            if (mContext instanceof Activity) {
                Activity activity = (Activity) mContext;
                if (!activity.isFinishing()) {
                    mLoadingDialog.show();
                }
            }else {
                mLoadingDialog.show();
            }
        }catch (Exception e) {

        }

        avLoadingIndicatorView.smoothToShow();
        mLoadingDialog.setOnKeyListener((dialogInterface, keyCode, keyEvent) -> {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                mLoadingDialog.dismiss();
                avLoadingIndicatorView.hide();
                return true;
            }
            return false;
        });

    }

    public void stopDialog() {
        try {
            if (mContext instanceof Activity) {
                Activity activity = (Activity) mContext;
                if (!activity.isFinishing()) {
                    if (mLoadingDialog != null) {
                        if (mLoadingDialog.isShowing()) {
                            mLoadingDialog.dismiss();
                        }
                    }
                }
            }else {
                if (mLoadingDialog != null) {
                    if (mLoadingDialog.isShowing()) {
                        mLoadingDialog.dismiss();
                    }
                }
            }
        }catch (Exception e) {

        }
    }
}
