package com.wasu.cs.mvp.presenter;

import android.util.SparseArray;

import com.wasu.cs.model.ChildrenChannelModel;
import com.wasu.cs.model.ChildrenChannelModel.DataBean;
import com.wasu.cs.model.ChildrenRecommendModel;
import com.wasu.cs.mvp.IView.IChildrenHomeView;
import com.wasu.cs.utils.JsonUtil;
import com.wasu.module.datafetch.DataFetchListener;
import com.wasu.module.datafetch.DataFetchModule;

import org.json.JSONObject;

import java.util.List;

/**
 * Created by chenming on 2016/11/7.
 *
 * @Description: 少儿频道首页presenter
 * @email chenming@wasu.com
 */

public class ChildrenHomePresenter extends BasePresenter<IChildrenHomeView> {

	private ChildrenChannelModel mModel;
	private String[] recUrls;


	public void getChildrenData(String url) {
		DataFetchModule.getInstance().fetchJsonGet(url, new DataFetchListener.JsonListener() {
			@Override
			public void onJsonGet(int i, String s, JSONObject jsonObject) {
				if (mModel == null && jsonObject != null) {
					mModel = JsonUtil.fromJson(jsonObject.toString(), ChildrenChannelModel.class);
					if (mModel != null) {
						if (ChildrenHomePresenter.this.getMvpView() != null) {
							ChildrenHomePresenter.this.getMvpView().onGetInfoBar(mModel.getData().getBody().getInfoBar());
							ChildrenHomePresenter.this.getMvpView().onGetCartoons(mModel.getData().getBody().getCartoons());
							ChildrenHomePresenter.this.getMvpView().onGetEntrys(mModel.getData().getBody().getEntrys());
							fetchCartoonsList(mModel);
						}
					} else {
						ChildrenHomePresenter.this.getMvpView().ongetDataFailed(new Throwable("ChildrenChannelHomeData fetch Failed"));
					}
				} else if (jsonObject==null){
					ChildrenHomePresenter.this.getMvpView().ongetDataFailed(new Throwable("Data fetch Failed"));
				}
			}
		});
	}

	private void fetchCartoonsList(ChildrenChannelModel model) {
		final int count = model.getData().getBody().getEntrys().size();
		List<DataBean.BodyBean.EntrysBean> entrysBeanList = model.getData().getBody().getEntrys();
		recUrls = new String[count];
		final SparseArray<List<ChildrenRecommendModel.DataBean.Cat>> recdatasp = new SparseArray<>();
		for (int i = 0; i < count; i++) {
			recUrls[i] = entrysBeanList.get(i).getRecommendUrl();
			final int pos = i;
			DataFetchModule.getInstance().fetchJsonGet(recUrls[i], new DataFetchListener.JsonListener() {
				@Override
				public void onJsonGet(int i, String s, JSONObject jsonObject) {
					if (jsonObject != null) {
						ChildrenRecommendModel recommendAsset =
								JsonUtil.fromJson(jsonObject.toString(), ChildrenRecommendModel.class);
						recdatasp.put(pos, recommendAsset.getData().getList());
						if (recdatasp.size() == count) {
							ChildrenHomePresenter.this.getMvpView().onGetRecommendData(recdatasp);
						}
					}
				}
			});

		}

	}


}
