package com.mgq.base.utils.progressdialog;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;


public class ProgressManager {

    private ProgressDialog progressDialog=null;
    private static ProgressManager instance;
    private ProgressManager(){
    }

    public static ProgressManager getInstance(){
        if(instance==null){
            instance=new ProgressManager();
        }
        return instance;
    }

    public void showProgress(Context mContext, final DialogCancelListener listener, String message, boolean cancelable){
        cancelProgress();
        progressDialog=new ProgressDialog(mContext);
        String msg = "Loading...";
        if (message != null && !message.isEmpty())
            msg = message;
        progressDialog.setMessage(msg);
        progressDialog.setCancelable(cancelable);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setOnCancelListener(arg0 -> {
            if(listener!=null&&progressDialog!=null){
                listener.onCancel();
            }
        });

        if (mContext instanceof Activity){
            Activity activity = (Activity) mContext;
            if (!activity.isFinishing()){
                progressDialog.show();
            }
        }else {
            progressDialog.show();
        }
    }

    public void setProgressMessage(String message){
        if (progressDialog != null && progressDialog.isShowing()){
            progressDialog.setMessage(message);
        }
    }

    public void cancelProgress(){
        if(progressDialog!=null){
            progressDialog.dismiss();
            progressDialog=null;
        }
    }

    public boolean isShowing(){
        boolean isShowing = false;
        if (progressDialog != null){
            isShowing = progressDialog.isShowing();
        }
        return isShowing;
    }

    public interface DialogCancelListener{
        public void onCancel();
    }
}