package com.zhaohaoting.framework.utils.observer;

import android.os.Handler;
import android.os.Looper;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

/**
 * author：Created by zhaohaoting on 2019/2/20 15:17
 * email：526309416@qq.com
 * desc：事件处理类
 */
public class ObserverManager {

    private static ObserverManager INSTANCE;
    private Map<String, List<Observer<?>>> eventParams = new Hashtable<>();
    private Handler threadHandler;

    private ObserverManager() {
    }

    public static ObserverManager getInstance() {
        if (INSTANCE == null) {
            synchronized (ObserverManager.class) {
                if (INSTANCE == null) {
                    INSTANCE = new ObserverManager();
                }
            }
        }
        return INSTANCE;
    }

    /**
     * 处理线程专用
     *
     * @return
     */
    private Handler getHandler() {
        if (threadHandler == null) {
            threadHandler = new Handler(Looper.getMainLooper());
        }
        return threadHandler;
    }

    /**
     * 注册事件
     *
     * @param event    事件标识
     * @param observer 删除事件
     */
    public void registerObserver(String event, Observer observer) {
        boolean hasKey = eventParams.containsKey(event);
        List<Observer<?>> observers = eventParams.get(event);
        if (hasKey && observers != null) {
            if (!observers.contains(observer)) {
                observers.add(observer);
            }
        } else {
            eventParams.put(event, new ArrayList<Observer<?>>() {{
                add(observer);
            }});
        }
    }

    /**
     * 删除事件
     *
     * @param event    事件标识
     * @param observer 删除事件
     */
    public void unregisterObserver(String event, Observer observer) {
        boolean hasKey = eventParams.containsKey(event);
        List<Observer<?>> observers = eventParams.get(event);
        if (hasKey && observers != null) {
            observers.remove(observer);
        }
    }

    /**
     * 发送事件提醒至主线程
     *
     * @param event 事件标识
     * @param data  附带数据
     */
    public void notifyObserver(String event, Object data) {
        List<Observer<?>> observers = eventParams.get(event);
        if (observers != null) {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                for (Observer observer : observers) {
                    observer.onEvent(event, data);
                }
            } else {
                getHandler().post(() -> {
                    for (Observer observer : observers) {
                        observer.onEvent(event, data);
                    }
                });
            }
        }
    }
}
