package com.wasu.cs.mvp.presenter;

import android.os.Handler;

import com.wasu.cs.model.CartoonListModel;
import com.wasu.cs.model.CatData;
import com.wasu.cs.mvp.IView.ICartoonListView;
import com.wasu.cs.protocol.CatProtocol;
import com.wasu.cs.utils.JsonUtil;
import com.wasu.module.datafetch.DataFetchListener;
import com.wasu.module.datafetch.DataFetchModule;

import org.json.JSONObject;

/**
 * Created by chenming on 2016/11/18.
 *
 * @Description: 动画列表页presenter
 * @email chenming@wasu.com
 */

public class CartoonListPresenter extends BasePresenter<ICartoonListView> {
	private CartoonListModel model;
	private CatProtocol mCatProtocol = new CatProtocol();

	public void getCartoonListData(String url, final Handler handler) {
		DataFetchModule.getInstance().fetchJsonGet(url, new DataFetchListener.JsonListener() {
			@Override
			public void onJsonGet(int i, String s, JSONObject jsonObject) {
				if (model == null && jsonObject != null) {
					model = JsonUtil.fromJson(jsonObject.toString(), CartoonListModel.class);
					if (model != null) {
						CartoonListPresenter.this.getMvpView().onGetDataSucceed(model);
					}

				}else {
					CartoonListPresenter.this.getMvpView().onGetDataFailed(new Throwable("CartoonList data fetch failed"));
				}
			}
		});
	}
	public void getCatData(String url , final int index){
		mCatProtocol.withUrl(url);
		mCatProtocol.fetchData(new Handler(), mCatProtocol.getRequestUrl(), new CatProtocol.CatFetchCallback() {
			@Override
			public void onResult(boolean successed, CatData catData) {
				if (successed && catData!=null){
					CartoonListPresenter.this.getMvpView().onGetCatData(catData,index);
				}else {
					CartoonListPresenter.this.getMvpView().onGetDataFailed(new Throwable("CartoonList catdata fetch failed"));
				}
			}
		});
	}

	@Override
	public void detachView() {
		super.detachView();
		if (model != null) {
			model = null;
		}
	}
}
