package com.wasu.cs.protocol;

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

import org.json.JSONArray;
import org.json.JSONObject;

import com.wasu.cs.model.CatModel;
import com.wasu.cs.model.HomeColumnModel;
import com.wasu.module.datafetch.DataFetchListener.JsonListener;
import com.wasu.module.datafetch.DataFetchModule;

public class HomeColumnProtocol extends BaseProtocol {
	private int total;
	private CatModel cat;
	private List<HomeColumnModel> columnList = new ArrayList<HomeColumnModel>();

	@Override
	public boolean from(JSONObject json) {
		boolean result = super.from(json);

		if (result) {
			json = json.optJSONObject("data");
			JSONObject jsonObj = null;
			JSONArray jsonArr = null;
			if (null != json) {
				total = json.optInt("total", 0);
				jsonObj = json.optJSONObject("cat");
				jsonArr = json.optJSONArray("elements");
			}

			if (jsonObj != null) {
				cat = new CatModel();
				cat.from(jsonObj);
			}

			if (null != jsonArr && jsonArr.length() > 0) {
				HomeColumnModel model = null;
				for (int i = 0, len = jsonArr.length(); i < len; i++) {
					model = new HomeColumnModel();

					if (model.from(jsonArr.optJSONObject(i))) {
						columnList.add(model);
					}
				}
			}
		}

		return result;
	}
	
	public void initChildrenTimeAndCorner(int carouselTime, Map<String, String> cornerIconMap) {
		for(HomeColumnModel model: columnList) {
			model.setCarouselTime(carouselTime);
			model.setCornerIconMap(cornerIconMap);
		}
	}

	public static void fetch(String url, final HomeColumnFetchCallback callback) {
		DataFetchModule.getInstance().fetchJsonGet(url, new JsonListener() {

			@Override
			public void onJsonGet(int retcode, String extraMsg,
					JSONObject jsonObj) {
				if (retcode == 0 && callback != null) {
					HomeColumnProtocol protocol = new HomeColumnProtocol();
					protocol.from(jsonObj);
					callback.onResult(protocol.successed(), protocol);
				} else {
					callback.onResult(false, null);
				}
			}
		});
	}

	public interface HomeColumnFetchCallback {
		public void onResult(boolean successed, HomeColumnProtocol homeColumnProtocol);
	}

	public int getTotal() {
		return total;
	}

	public CatModel getCat() {
		return cat;
	}

	public List<HomeColumnModel> getColumnList() {
		return columnList;
	}

}
