package com.atmob.keyboard_android.util.loading;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.Window;

/**
 * Loading控制器
 */
public class WaitLoadingController {
    /**
     * 一定要显示够指定时间
     */
    private static final long LOAD_MIN_TIME = 100;

    private LoadingDialog vLoadingDialog;

    private final Handler mMainHandler;

    /**
     * 开始展示的时间
     */
    private long showTime;

    /**
     * 是否可用
     */
    private boolean isEnable = true;

    public WaitLoadingController(Context context, Window hostWindow) {
        mMainHandler = new Handler(Looper.getMainLooper());
        setup(context, hostWindow);
    }

    private void setup(Context context, Window hostWindow) {
        ensureMainThreadRun(() -> {
            vLoadingDialog = new LoadingDialog(context, hostWindow);
        });
    }

    /**
     * 设置是否可用
     */
    public void setEnable(boolean enable) {
        this.isEnable = enable;
    }

    public void showWait() {
        ensureMainThreadRun(() -> {
            if (!isEnable) {
                return;
            }
            if (vLoadingDialog != null && !vLoadingDialog.isShowing()) {
                showTime = System.currentTimeMillis();
                vLoadingDialog.show();
            }
        });
    }

    public void hideWait() {
        long currentTime = System.currentTimeMillis();
        Runnable runnable = () -> {
            if (vLoadingDialog != null) {
                vLoadingDialog.dismiss();
            }
        };
        // 显示到调用结束，间隔的时间
        long intervalTime = currentTime - showTime;
        // 最少要显示够的时间
        long leastTime = showTime + LOAD_MIN_TIME;
        // 如果显示时间比最大时间大，则马上隐藏
        if (intervalTime >= LOAD_MIN_TIME) {
            ensureMainThreadRun(runnable);
        } else {
            // 否则，补够时间，再隐藏
            ensureMainThreadRun(runnable, leastTime - currentTime);
        }
    }

    private void destroy() {
        ensureMainThreadRun(() -> {
            hideWait();
            vLoadingDialog = null;
        });
    }

    /**
     * 确保主线程执行
     */
    public void ensureMainThreadRun(Runnable runnable) {
        if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
            runnable.run();
        } else {
            mMainHandler.post(runnable);
        }
    }

    /**
     * 延时执行，确保在主线程
     */
    public void ensureMainThreadRun(Runnable runnable, long delayMillis) {
        mMainHandler.postDelayed(runnable, delayMillis);
    }
}