package com.wasu.cs.protocol;

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

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

import com.wasu.cs.model.AssetDetailModel;
import com.wasu.cs.model.TagModel;
import com.wasu.module.datafetch.DataFetchListener.JsonListener;
import com.wasu.module.datafetch.DataFetchModule;

public class AssetDetailProtocol extends BaseProtocol {

	private String assetTagsUrl;
	private String recommendUrl;
	private AssetDetailModel assetDetailModel;
	private List<TagModel> tagList = new ArrayList<TagModel>();

	@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) {
				assetTagsUrl = json.optString("assetTagsUrl", "");
				recommendUrl = json.optString("recommendUrl", "");

				jsonObj = json.optJSONObject("detail");
				jsonArr = json.optJSONArray("tags");
			}

			if (jsonObj != null) {
				assetDetailModel = new AssetDetailModel();
				assetDetailModel.from(jsonObj);
			}

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

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

		return result;
	}
	
	public static void fetch(String url, final AssetDetailFetchCallback callback) {
		DataFetchModule.getInstance().fetchJsonGet(url, new JsonListener() {
			
			@Override
			public void onJsonGet(int retcode, String extraMsg, JSONObject jsonObj) {
				
				if(callback == null) {
					try {
						throw new Exception();
					} catch (Exception e) {
						e.printStackTrace();
					}
					
					return;
				}
				
				if(retcode == 0) {
					AssetDetailProtocol protocol = new AssetDetailProtocol();
					protocol.from(jsonObj);
					callback.onResult(protocol.successed(), protocol);
				} else {
					callback.onResult(false, null);
				}
			}
		});
	}
	
	public interface AssetDetailFetchCallback {
		public void onResult(boolean successed, AssetDetailProtocol assetDetailProtocol);
	}

	public String getAssetTagsUrl() {
		return assetTagsUrl;
	}

	public String getRecommendUrl() {
		return recommendUrl;
	}

	public AssetDetailModel getAssetDetailModel() {
		return assetDetailModel;
	}

	public List<TagModel> getTagList() {
		return tagList;
	}

}
