package com.wasu.cs.ui;


import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.wasu.common.WError;
import com.wasu.cs.model.DemandList;
import com.wasu.cs.model.DemandList.Datum;
import com.wasu.cs.model.DemandProgramColumn;
import com.wasu.cs.model.DemandProgramColumn.Asset;
import com.wasu.cs.model.DemandProgramColumn.Cat;
import com.wasu.cs.model.DemandProgramColumn.Data;
import com.wasu.cs.widget.FocusGridViewEx;
import com.wasu.frescoimagefetchermodule.FrescoImageFetcherModule;
import com.wasu.module.datafetch.DataFetchListener.JsonListener;
import com.wasu.module.datafetch.DataFetchModule;
import com.wasu.module.log.WLog;

import org.json.JSONObject;

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

import cn.com.wasu.main.Common;
import cn.com.wasu.main.ErrorMap;
import cn.com.wasu.main.IntentConstant;
import cn.com.wasu.main.IntentMap;
import cn.com.wasu.main.R;

/**
 * 兼容新CMS从经纬导入的数据结构新增的activity 综艺节目的三级列表
 * 
 * @author danxingxi 2015/8/27
 * 
 */
public class ActivityColumn extends ActivityBase {

	private final static String TAG = "com.wasu.cs.ui.ActivityColumn";

	private String JSON_URL = "http://121.40.195.74/?s=2002&p=sntAssetDetail&k=1&v=1&catId=297459&assetId=1073456";
	/** 存放请求返回的json数据对象 **/
	private DemandProgramColumn mDemandProgramColumn = new DemandProgramColumn();

	/***** 缓存page状态 *****/
	/** json中数据item的总个数 **/
	private int totalCount = 0;
	/** 默认最大的页数 **/
	private int pageSize = Common.DEFAULT_PAGE_SIZE;
	/** 当前获取的页码 **/
	private int currentFetchPage = -1;
	/** 可以按照页面的不同来存放页码对应的item **/
	private SparseArray<DemandProgramColumn> mPageList = new SparseArray<DemandProgramColumn>();
	
	private DemandList demandList = new DemandList();

	private TextView mTitleView;
	private FocusGridViewEx mListView;
	private SimpleDraweeView mBgImageView;
	private LayoutInflater lInflater;
	private TextView tv_EmptyView;
	/**是否从首页直接跳转过来**/
	private boolean isFormHomePage = false;

	@Override
	protected void doCreate(Bundle savedInstanceState) {
		WLog.i(TAG,"doCreate()");

		setContentView(R.layout.activity_column);

		reset();
		initData();
		initView();
		/** 第一次进去先获取第一页的数据 **/
		fetchPage(1);
	}

	/**
	 * 初始化数据
	 */
	private void initData() {

		JSON_URL = getIntent().getStringExtra(IntentConstant.DATAURI.value());
		String formWhereStr = getIntent().getStringExtra("Column_Detail_List1");
		if(formWhereStr != null && formWhereStr.equalsIgnoreCase("Column_Detail_List1")){
			isFormHomePage = true;
		}

		if (TextUtils.isEmpty(JSON_URL)) {
			showErrorExitDlg("没有数据源!");
			return;
		}
	}

	/**
	 * 根据页面码数获取数据
	 * 
	 * @param page
	 */
	private void fetchPage(final int page) {
		/* 第一次进入加载数据显示loading */
		if (page == 1) {
			showLoading();
		}
		/* 如果请求的页码等于当前显示的页码就返回不做请求 */
		if (currentFetchPage == page) {
			return;
		}
		currentFetchPage = page;
		/* 拼接URL地址，添加页码和一页item的最大数量 */
		Uri fetchUri = Uri.parse(JSON_URL);
		fetchUri = fetchUri.buildUpon()
				.appendQueryParameter("page", String.valueOf(page))
				.appendQueryParameter("psize", String.valueOf(pageSize))
				.build();
		
		DataFetchModule.getInstance().fetchJsonGet(fetchUri.toString(),
				new JsonListener() {
					@Override
					public void onJsonGet(int retcode, String extraMsg,
							JSONObject jsondata) {
						currentFetchPage = -1;
						if (page == 1) {
							hideLoading();
							if (retcode != 0) {
								showErrorExitDlg(ErrorMap.mapError(ActivityColumn.this, retcode, extraMsg));
								return;
							}
						}
						try {
							Gson gson = new Gson();
							mDemandProgramColumn = gson.fromJson(jsondata.toString(), DemandProgramColumn.class);
							/**
							 * 防止用户停留在集合资产列表的时候，后台下架资产后出现操作异常
							 */
							if(mDemandProgramColumn.getData().getAssets().size()<1 || mDemandProgramColumn.getData().getAssets().isEmpty()){
								return;
							}
							
							if (page == 1) {
								showView();
								totalCount = mDemandProgramColumn.getData().getTotal();
								if (totalCount == 0) {
									tv_EmptyView.setVisibility(View.VISIBLE);
									//mListView.setEmptyView(tv_EmptyView);
								}
							}
							mPageList.append(page, mDemandProgramColumn);
							append(mDemandProgramColumn);
							notifyDataChanged();

						} catch (Exception e) {
							e.printStackTrace();
							WLog.e(TAG, page + "Json data error");
							showErrorExitDlg(ErrorMap.mapError(ActivityColumn.this, WError.ERROR_INVALID_DATA, extraMsg));
						}
					}
				});

	}

	/**
	 * 获取单个资产item
	 * 
	 * @param index
	 * @return
	 */
	private Asset getAssetItem(int index) {
		/* 如果获取的item不在当前页，就去fetch下一页 */
		int page = index / pageSize + 1;
		DemandProgramColumn mDemandProgramColumn = mPageList.get(page);
		if (mDemandProgramColumn == null) {  //下一页的数据为空就去获取
			fetchPage(page);
			return null;
		} else {
				/**需要显示的item超出当前页，在下一页**/
				index = index % pageSize;
				if (index >= mDemandProgramColumn.getData().getAssets().size()) {
					return null;
				} else {
					return mDemandProgramColumn.getData().getAssets().get(index);
				}
		}
	}

	/**
	 * 当list需要数据发生改变时通知适配器
	 */
	private void notifyDataChanged() {
		if (mListView != null && mListView.getAdapter() != null) {
			((mListAdapter) mListView.getAdapter()).notifyDataSetChanged();
		}
	}

	/**
	 * 初始化控件
	 */
	private void initView() {
		mTitleView = (TextView) findViewById(R.id.titleView);
		if(isFormHomePage){
			mTitleView.setVisibility(View.GONE);
		}
		mListView = (FocusGridViewEx) findViewById(R.id.listView);
		mBgImageView = (SimpleDraweeView) findViewById(R.id.bgImage);
		tv_EmptyView = (TextView) findViewById(R.id.tv_EmptyView);
		lInflater = LayoutInflater.from(ActivityColumn.this);
		
		mListView.setFocusHightlightDrawable(R.drawable.tv_select_focus);
		mListView.postAnimation(200, null);
//		mListView.setFocusShadowDrawable(R.drawable.focus_shadow);
		mListView.setAdapter(new mListAdapter());
//		mListView.setOnScrollListener(new PauseOnScrollListener(ImageFetcherModule.getInstance().getImageLoader(), true, true));
		/** item点击监听器，点击转到播放器播放 **/
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view,
					int i, long l) {
				/**防止资源不存在，但是页面显示有item的位置时候用户点击报错**/
				if(null == getAssetItem(i)){
					postMessage(getString(R.string.error_http_404));
				}else{
				/*IntentMap.startIntent(ActivityColumn.this, null,
						getAssetItem(i).getLayout(), getAssetItem(i)
								.getJsonUrl(), null);*/
					Intent intent = new Intent();
					intent.putExtra(IntentConstant.PLAY_TYPE.value(), ActivityPlayer.PLAY_TYPE_LOOP);
					intent.putExtra(IntentConstant.PLAY_INDEX.value(), i);
					intent.putExtra(ActivityPlayer.ASSET_LIST, (Serializable) demandList);
					
					IntentMap.startIntent(ActivityColumn.this, intent, null, null, ActivityPlayer.class);
				}
			}
		});
	}

	/**
	 * 重置listview
	 */
	private void reset() {
		if (mListView != null) {
			mListView.clearFocus();
			mListView.removeAllViews();
		}
		totalCount = 0;
		currentFetchPage = -1;

		JSON_URL = null;
		notifyDataChanged();
	}

	/**
	 * 
	 */
	private void showView() {
		mTitleView.setText(mDemandProgramColumn.getData().getCat()
				.getCatName());
		FrescoImageFetcherModule.getInstance().attachImage(
				mDemandProgramColumn.getData().getCat().getBgImage(),
				mBgImageView);
	}
	
	private void append(DemandProgramColumn demandProgramColumn) {
		Datum data = demandList.getDatum();
		Data d = demandProgramColumn.getData();
		
		if (data == null) {
			data = new Datum();
			if (d != null) {
				Cat cat = d.getCat();
				if (cat != null) {
					data.setCatId(cat.getCatId());
					data.setCatName(cat.getCatName());
				}
			}
			demandList.setDatum(data);
		}
		
		List<DemandList.Asset> assets = data.getAssets();
		
		if (assets == null) {
			assets = new ArrayList<DemandList.Asset>();
			data.setAssets(assets);
		}
		
		List<Asset> l = d.getAssets();
		if (l != null && l.size() != 0) {
			
			for (Asset asset : l) {
				DemandList.Asset a = new DemandList.Asset();
				a.setCatId(asset.getCatId());
				a.setDatetime(asset.getDatetime());
				a.setId(asset.getId());
				a.setPicUrl(asset.getPicUrl());
				a.setTitle(asset.getTitle());
				a.setSummary(asset.getSummary());
				a.setJsonUrl(asset.getJsonUrl());
				a.setLayout(asset.getLayout());
				
				assets.add(a);
			}
		}

		data.setTotal(assets.size());
	}

	/**
	 * 内部类实现listview的适配器
	 */
	class mListAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return totalCount;
		}

		@Override
		public Object getItem(int position) {
			return getAssetItem(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Asset assetItem = (Asset) getItem(position);
			if (convertView == null) {
				convertView = lInflater.inflate(R.layout.item_channel_news_list, null);
			}
			SimpleDraweeView vImage = (SimpleDraweeView) convertView.findViewById(R.id.ivPic);
			TextView tvName = (TextView) convertView.findViewById(R.id.name);

			if (convertView.getTag() != null) {
				int mHoldPos = (Integer) convertView.getTag();
				String name = tvName.getText().toString();
				if (mHoldPos == position && !TextUtils.isEmpty(name)
						&& assetItem != null
						&& name.equals(assetItem.getTitle())) {
					return convertView;
				} else {
					vImage.setImageBitmap(null);
				}
			}
			if (assetItem != null) {
				FrescoImageFetcherModule.getInstance().attachImage(assetItem.getPicUrl(), vImage,
						getResources().getDimensionPixelSize(R.dimen.d_5dp));
				tvName.setText(assetItem.getTitle());
			} else {
				tvName.setText("");
			}
			convertView.setTag(position);
			return convertView;
		}

	}
}
