package com.wasu.cs.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

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

import com.wasu.common.WError;
import com.wasu.module.datafetch.DataFetchException;
import com.wasu.module.datafetch.ObjectBase;

public class MovieRecommend extends ObjectBase {
	
	private static final long serialVersionUID = 1L;

	private static final String TAG = MovieRecommend.class.getSimpleName();
	
	private List<MovieRecommendItem> movieRecommends = null;
	
	public List<MovieRecommendItem> getMovieRecommend() {
		return movieRecommends;
	}

	@Override
	public void createFromResponse(String response) throws DataFetchException {
		
		try {
			JSONObject root = new JSONObject(response);
			
			int code = root.optInt("code");
			if (code != 200) {
				throw new DataFetchException(WError.ERROR_INVALID_DATA, root.optString("message"));
			}
			
			movieRecommends = new ArrayList<MovieRecommendItem>();
			JSONArray list = root.optJSONObject("data").optJSONArray("elements");
			
			if (list == null){
				list = root.optJSONObject("data").optJSONArray("childCats");
			}
			
			int length = list.length();
			for (int i = 0; i < length; i++) {
				JSONObject item = list.optJSONObject(i);
				
				MovieRecommendItem obj = new MovieRecommendItem();
				obj.setJsonUrl(item.optString("jsonUrl"));
				obj.setLayoutCode(item.optString("layout"));
				obj.setName(item.optString("name"));
				
				movieRecommends.add(obj);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new DataFetchException(WError.ERROR_INVALID_DATA, null);
		}
	}
	
	public class MovieRecommendItem implements Serializable {
		
		private static final long serialVersionUID = 1L;
		
		private String jsonUrl;
		private String layoutCode;
		private String name;

		public String getJsonUrl() {
			return jsonUrl;
		}
		
		public void setJsonUrl(String url) {
			jsonUrl = url;
		}
		
		public String getLayoutCode() {
			return layoutCode;
		}

		public void setLayoutCode(String layoutCode) {
			this.layoutCode = layoutCode;
		}
		
		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}
	}

}
