package com.secspace.lib.common.dialog;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.secspace.lib.common.dialog.other.DialogUIUtils;
import com.secspace.log.Log;


/**
 * Created by SKR-CYW on 2017/11/22.
 */
public class LoadingDialog {

    private static final String TAG = "SwitcherDialog";
    @SuppressLint("StaticFieldLeak")
    private static LoadingDialog INST;

    public static LoadingDialog getInstance(Context context) {
        if (INST == null) {
            synchronized (LoadingDialog.class) {
                if (INST == null) {
                    INST = new LoadingDialog(context.getApplicationContext());
                }
            }
        }
        return INST;
    }

    private Context mContext;
    private Dialog mDialog;
    private Handler mHandler;
    private static final int TIMEOUT = 1;

    private LoadingDialog(Context context) {
        mContext = context.getApplicationContext();
        mHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case TIMEOUT:
                        Log.d(TAG, "switch dialog timeout");
                        dismiss();
                        return true;
                    default:
                        return false;
                }
            }
        });
    }

    public void show(String text) {
        if (mDialog == null) {
            mDialog = DialogUIUtils.showLoading(mContext, text, true, false, false, true).show();
        }
        if (!mDialog.isShowing()) {
            try {
                mDialog.show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        mHandler.removeMessages(TIMEOUT);
        mHandler.sendEmptyMessageDelayed(TIMEOUT, 10000);
    }

    public void dismiss() {
        mHandler.removeMessages(TIMEOUT);
        if (mDialog != null && mDialog.isShowing()) {
            try {
                DialogUIUtils.dismiss(mDialog);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (mDialog != null) {
            mDialog = null;
        }
    }
}