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.
 */
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();
    }
}
