package com.ez.ertc.meeting.widget;

import android.app.Activity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.ez.ertc.meeting.R;

/**
 * @author xiezuoyuan
 * @time 2018/9/25 10:45
 */
public class WaitingDialog {

    /**
     * 显示加载圈
     * @param activity
     * @param cancelable
     */
    public static void showWaitingDialog(final Activity activity , String text, final boolean cancelable){
        try {
            if (activity == null || isLoading(activity)){
                return;
            }
            FrameLayout root = activity.getWindow().getDecorView().findViewById(android.R.id.content);
            if (root != null && root.findViewById(R.id.rlLoadingRoot) == null){
                View loadingView = LayoutInflater.from(activity).inflate(R.layout.ezm_waiting_dialog, null);
                //遮罩层设置点击事件，拦截底层视图的点击事件
                loadingView.findViewById(R.id.rlLoadingRoot).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (cancelable){
                            dismissWaitingDialog(activity);
                        }
                    }
                });
                TextView tvMessage = loadingView.findViewById(R.id.tvMessage);
                if (!TextUtils.isEmpty(text)){
                    tvMessage.setText(text);
                    tvMessage.setVisibility(View.VISIBLE);
                } else {
                    tvMessage.setVisibility(View.GONE);
                }
                root.removeView(loadingView);
                root.addView(loadingView);
            }
        } catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 隐藏加载圈
     * @param activity
     */
    public static void dismissWaitingDialog(Activity activity){
        try {
            if (activity == null){
                return;
            }

            if ((activity.isFinishing())) {
                return;
            }
            FrameLayout root = activity.getWindow().getDecorView().findViewById(android.R.id.content);
            if (root != null){
                View loadingView = root.findViewById(R.id.rlLoadingRoot);
                if (loadingView != null) {
                    root.removeView(loadingView);
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 加载圈是否正在显示
     * @param activity
     * @return
     */
    public static boolean isLoading(Activity activity) {
        FrameLayout root = activity.getWindow().getDecorView().findViewById(android.R.id.content);
        if (root != null){
            View loadingView = root.findViewById(R.id.rlLoadingRoot);
            return loadingView != null && root.indexOfChild(loadingView) != -1;
        }
        return false;
    }
}
