package com.secspace.lib.common.dialog;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
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.env.AttrApn;
import com.secspace.lib.common.event.PrepareSimEvent;
import com.secspace.lib.common.event.SimReadyWhenEnterEvent;
import com.secspace.lib.common.utils.Prefs;
import com.secspace.log.Log;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

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

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

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

    private Context mContext;
    private View mView;
    private Dialog mDialog;
    private TextView mMessageView;
    private CharSequence mMessage;
    private Handler mHandler;
    private static final int TIMEOUT = 1;

    private SwitcherDialog(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("TimeOut");
                        return true;
                    default:
                        return false;
                }
            }
        });
    }

    /**
     * @param message
     * @param moment  进入/退出/超时
     */
    public void show(String message, String moment) {
        if (mDialog == null) {
            mView = LayoutInflater.from(mContext).inflate(R.layout.common_switcher_dialog, null);
            mMessageView = mView.findViewById(R.id.tv_msg);
            mDialog = new AlertDialog.Builder(mContext, R.style.Theme_AppCompat_Dialog_Alert)
                    .setView(mView)
                    .setCancelable(false)
                    .create();
            mMessage = mContext.getText(R.string.common_switching);
            Window window = mDialog.getWindow();
            if (window != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    window.setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
                } else {
                    window.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                }
            }
        }
        mMessageView.setText(message != null ? message : mMessage);
        if (!mDialog.isShowing()) {
            try {
                mDialog.show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 超时
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mHandler.removeMessages(TIMEOUT);
        mHandler.sendEmptyMessageDelayed(TIMEOUT, 10000);
    }

    /**
     * @param moment 进入/退出/超时
     */
    public void dismiss(String moment) {
        EventBus.getDefault().unregister(this);
        mHandler.removeMessages(TIMEOUT);
        if (mDialog != null && mDialog.isShowing()) {
            try {
                mDialog.dismiss();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (mDialog != null) {
            mDialog = null;
            mView = null;
            mMessageView = null;
        }
    }

    /**
     * 切换数据流量卡
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPrepareSim(PrepareSimEvent e) {
        show("正在准备网络，请稍后...", "");
    }

}