package com.secspace.lib.common.dialog;

import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Point;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.secspace.lib.common.R;
import com.secspace.lib.common.views.DotRotateProgress;

/**
 * Created by cyw_m on 2018/4/16.
 */

public class DotRotateDialog implements DialogInterface.OnDismissListener {
    private Activity mAct;
    private AlertDialog mDialog;
    private View mView;
    private DotRotateProgress mDotRotateProgress;
    private TextView mTvMsg;

    public DotRotateDialog(Activity activity) {
        this.mAct = activity;
    }

    private void initView() {
        mView = mAct.getLayoutInflater().inflate(R.layout.common_dialog_dot_rotate, null);
        mDotRotateProgress = mView.findViewById(R.id.dot_rotate_progress);
        mTvMsg = mView.findViewById(R.id.tv_msg);
    }

    public DotRotateDialog show(String msg, boolean cancelable) {
        if (mDialog == null) {
            initView();
            AlertDialog.Builder builder = new AlertDialog.Builder(mAct);
            builder.setView(mView);
            builder.setCancelable(cancelable);
            builder.setOnDismissListener(this);
            mDialog = builder.create();
        }
        if (!mDialog.isShowing()) {
            mDialog.show();
//            setDialogWindow();
            mDotRotateProgress.startDotAnimator();
            if (!TextUtils.isEmpty(msg)) {
                mTvMsg.setText(msg);
            }
        }
        return this;
    }

    private void setDialogWindow(){
        Window window = mDialog.getWindow();
        Display display = mAct.getWindowManager().getDefaultDisplay();
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        Point point = new Point();
        display.getSize(point);
        layoutParams.width = point.x;
        layoutParams.height = point.y;
        layoutParams.gravity = Gravity.CENTER;
        window.setAttributes(layoutParams);
    }

    public void dismiss() {
        if (mDialog != null && mDialog.isShowing())
            mDialog.dismiss();
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        mAct = null;
        mView = null;
        mDotRotateProgress = null;
        mTvMsg = null;
        mDialog = null;
    }
}
