package com.gh.gamecenter.game;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;

import com.gc.materialdesign.views.ProgressBarCircularIndeterminate;
import com.gh.base.AppController;
import com.gh.base.BaseFragment;
import com.gh.common.util.DownloadItemUtils;
import com.gh.download.DataWatcher;
import com.gh.download.DownloadEntity;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.R;
import com.gh.gamecenter.entity.ApkEntity;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.eventbus.EBDownloadStatus;
import com.gh.gamecenter.eventbus.EBNetworkState;
import com.gh.gamecenter.eventbus.EBPackage;
import com.gh.gamecenter.eventbus.EBReuse;
import com.gh.gamecenter.eventbus.EBUISwitch;

/**
 * 
 * @author 温冠超
 * @email 294299195@qq.com
 * @date 2015-8-8
 * @update 2015-8-11
 * @des 主页插件fragment
 */
public class Game3Fragment extends BaseFragment implements OnRefreshListener {

	public static final String TAG = Game3Fragment.class.getSimpleName();

	private SwipeRefreshLayout fm_game_swipe_refresh;
	private RecyclerView fm_game_rv_list;
	private Game3FragmentAdapter adapter;
	private LinearLayoutManager layoutManager;
	private LinearLayout reuse_no_connection;
	private ProgressBarCircularIndeterminate fm_game_pb_loading;

	private boolean isEverpause;

	private Handler handler = new Handler();

	// 黄壮华 添加观察者 修改2015/8/15
	private DataWatcher dataWatcher = new DataWatcher() {
		@Override
		public void onDataChanged(DownloadEntity downloadEntity) {
			if (!fm_game_swipe_refresh.isRefreshing()) {
				Integer location = adapter.getLocationMap().get(downloadEntity.getName());
				if (location != null) {
					GameEntity detailedEntity = adapter.getList().get(location);
					if (detailedEntity != null) {
						DownloadItemUtils.processDate(getActivity(), detailedEntity,
								downloadEntity, adapter, location);
					}
				}
			}
		}
	};

	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		init(R.layout.fragment_game);

		isEverpause = false;

		reuse_no_connection.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				fm_game_swipe_refresh.setRefreshing(true);
				fm_game_rv_list.setVisibility(View.VISIBLE);
				fm_game_pb_loading.setVisibility(View.VISIBLE);
				reuse_no_connection.setVisibility(View.GONE);
				handler.postDelayed(runnable, 1000);
			}
		});

		fm_game_swipe_refresh.setColorSchemeResources(R.color.theme);
		fm_game_swipe_refresh.setOnRefreshListener(this);

		fm_game_rv_list.setHasFixedSize(true);
		layoutManager = new LinearLayoutManager(getActivity());
		fm_game_rv_list.setLayoutManager(layoutManager);
		// 黄壮华 传递引用 修改2015/8/15
		adapter = new Game3FragmentAdapter(Game3Fragment.this, false);
		fm_game_rv_list.setAdapter(adapter);
		fm_game_rv_list.setOnScrollListener(new RecyclerView.OnScrollListener() {
			@Override
			public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
				super.onScrollStateChanged(recyclerView, newState);
				if (newState == RecyclerView.SCROLL_STATE_IDLE
						&& layoutManager.findLastVisibleItemPosition() == adapter
								.getList().size()) {
					if (!adapter.isRemove() && !adapter.isLoading()) {
						adapter.addList(adapter.getList().size());
					}
				}
			}

		});
	}

	@Override
	public void loadDone() {
		if (fm_game_swipe_refresh != null && fm_game_swipe_refresh.isRefreshing()) {
			fm_game_swipe_refresh.setRefreshing(false);
		}
		if (fm_game_pb_loading != null && fm_game_pb_loading.getVisibility() == View.VISIBLE) {
			fm_game_pb_loading.setVisibility(View.GONE);
		}
	}

	@Override
	public void loadError() {
		if (fm_game_swipe_refresh != null && fm_game_swipe_refresh.isRefreshing()) {
			fm_game_swipe_refresh.setRefreshing(false);
		}
		if (fm_game_pb_loading != null && fm_game_pb_loading.getVisibility() == View.VISIBLE) {
			fm_game_pb_loading.setVisibility(View.GONE);
		}
		fm_game_rv_list.setVisibility(View.GONE);
		reuse_no_connection.setVisibility(View.VISIBLE);
	}

	//下载被删除事件
	public void onEventMainThread(EBDownloadStatus status) {
		if ("delete".equals(status.getStatus())) {
			DownloadManager.getInstance(getActivity()).removePlatform(status.getName(), status.getPlatform());

			Integer location = adapter.getLocationMap().get(status.getName());
			if (location != null) {
				int index = location;

				GameEntity detailedEntity = adapter.getList().get(index);
				if (TextUtils.isEmpty(status.getPlatform())) {
					detailedEntity.getEntryMap().remove("官方版");
				} else {
					detailedEntity.getEntryMap().remove(status.getPlatform());
				}
				adapter.notifyItemChanged(index);
			}
		}
	}

	// 打开下载按钮事件
	public void onEventMainThread(EBReuse reuse) {
		if ("Refresh".equals(reuse.getType()) && adapter != null) {
			adapter.notifyItemRangeChanged(0, adapter.getItemCount());
		}
	}

	//安装、卸载事件
	public void onEventMainThread(EBPackage busFour) {
		String name = adapter.getNameMap().get(busFour.getPackageName());
		if (name != null) {
			int location = adapter.getLocationMap().get(name);
			if ("安装".equals(busFour.getType())) {
				GameEntity detailedEntity = adapter.getList().get(location);
				for (ApkEntity apkEntity : detailedEntity.getApk()) {
					if (apkEntity.getPackageName().equals(busFour.getPackageName())) {
						detailedEntity.getEntryMap().remove(apkEntity.getPlatform());
						adapter.notifyItemChanged(location);
						break;
					}
				}
			} else if ("卸载".equals(busFour.getType())) {
				adapter.notifyItemChanged(location);
			}
		}
	}

	//连接上网络事件
	public void onEventMainThread(EBNetworkState busNetworkState) {
		if (busNetworkState.isNetworkConnected()) {
			if (reuse_no_connection.getVisibility() == View.VISIBLE) {
				fm_game_swipe_refresh.setRefreshing(true);
				fm_game_rv_list.setVisibility(View.VISIBLE);
				fm_game_pb_loading.setVisibility(View.GONE);
				reuse_no_connection.setVisibility(View.GONE);
				handler.postDelayed(runnable, 1000);
			} else if (adapter.isNetworkError()) {
				adapter.setNetworkError(false);
				adapter.notifyItemChanged(adapter.getItemCount() - 1);
				adapter.addList(adapter.getList().size());
			}
		}
	}

	public void onEventMainThread(EBUISwitch busNine) {
		if ("GameFragment".equals(busNine.getFrom())) {
			if (busNine.getPosition() == 2) {
				if (fm_game_pb_loading.getVisibility() == View.VISIBLE) {
					adapter.load();
				}
			}
		}
	}

	public boolean isEverpause() {
		return isEverpause;
	}

	@Override
	public void onResume() {
		super.onResume();
		if (isEverpause) {
			for (GameEntity entity : adapter.getList()) {
				entity.setEntryMap(DownloadManager.getInstance(getActivity()).getEntryMap(entity.getName()));
			}
			adapter.notifyDataSetChanged();
		}
		isEverpause = false;
		DownloadManager.getInstance(getActivity()).addObserver(dataWatcher);
	}

	@Override
	public void onPause() {
		super.onPause();
		isEverpause = true;
		DownloadManager.getInstance(getActivity()).removeObserver(dataWatcher);
	}

	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			if (!isDestroy) {
				adapter = new Game3FragmentAdapter(Game3Fragment.this, true);
				fm_game_rv_list.setAdapter(adapter);
			}
		}
	};

	@Override
	public void onRefresh() {
		handler.postDelayed(runnable, 1000);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		AppController.canclePendingRequests(TAG);
		fm_game_rv_list = null;
		fm_game_swipe_refresh = null;
		adapter = null;
		layoutManager = null;
		reuse_no_connection = null;
		handler = null;
		dataWatcher = null;
		fm_game_pb_loading = null;
	}

}
