package tech.starwin.utils;

import java.util.HashMap;
import java.util.Map;

import tech.starwin.base.BasePresenter;
import tech.starwin.mvp.IView;

/**
 * Created by SiKang on 2018/9/16.
 * 创建和缓存Presener实例
 */
public class PresenterHoler {

    private Map<String, BasePresenter> presenterMap;

    private IView view;

    public PresenterHoler(IView view) {
        this.view = view;
        presenterMap = new HashMap<>();
    }

    /**
     * 获取一个指定类型的Presenter实例，缓存中没有则创建一个
     */
    public <P extends BasePresenter> P getPresenter(Class<P> clz) {
        P presenter = null;
        if (presenterMap.containsKey(clz.getName())) {
            presenter = (P) presenterMap.get(clz.getName());
        } else {
            try {
                presenter = clz.newInstance();
                presenter.bindIView(view);
                presenterMap.put(clz.getName(), presenter);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return presenter;
    }

    public void onDestory() {
        for (String key : presenterMap.keySet()) {
            presenterMap.get(key).onDestory();
        }
        presenterMap.clear();
    }
}
