package com.mayi.fastdevelop.view;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mayi.fastdevelop.R;


/**
 * 通用的加载弹框
 */


public class LoadingDialog {

    private static final String TIP_STR = "加载中";
    private Context mContext;
    private String mTip = TIP_STR;
    private boolean mCanTouchOutsideCancel = false;
    private boolean mIsShowTip = true;

    private LoadingDialog(Context context) {
        this.mContext = context;
    }

    public static LoadingDialog init(Context context) {
        return new LoadingDialog(context);
    }

    public LoadingDialog setTip(String tip) {
        this.mTip = tip;
        return this;
    }

    public LoadingDialog setCanTouchOutsideCancel(boolean outsideCancel) {
        this.mCanTouchOutsideCancel = outsideCancel;
        return this;
    }

    public LoadingDialog isShowTipMsg(boolean isShow) {
        this.mIsShowTip = isShow;
        return this;
    }

    public Dialog show() {
        return createDialog();
    }

    private Dialog createDialog() {
        if (mContext != null) {
            if (mContext instanceof Activity) {
                if (!((Activity) mContext).isFinishing()) {
                    LayoutInflater layoutInflater = LayoutInflater.from(mContext);
                    View view = layoutInflater.inflate(R.layout.dialog_common_loading, null);
                    if (mIsShowTip) {
                        TextView tvTip = view.findViewById(R.id.tv_common_loading_tip_msg);
                        tvTip.setText(mTip);
                        tvTip.setVisibility(View.VISIBLE);
                    }
                    Dialog dialog = new Dialog(mContext, R.style.style_common_loading_dialog);
                    dialog.setCanceledOnTouchOutside(mCanTouchOutsideCancel);
                    dialog.setCancelable(mCanTouchOutsideCancel);
                    dialog.setContentView(view, new LinearLayout.LayoutParams(dip2px(100), dip2px(100)));
                    dialog.show();
                    return dialog;
                }
            }
        }
        return null;
    }

    private int dip2px(int dpValue) {
        final float scale = mContext.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
