package com.gh.gamecenter.download;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.util.ArrayMap;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gh.common.constant.Constants;
import com.gh.common.util.PackageUtils;
import com.gh.download.DataWatcher;
import com.gh.download.DownloadEntity;
import com.gh.download.DownloadManager;
import com.gh.download.DownloadStatus;
import com.gh.gamecenter.MainActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.eventbus.EBDownloadChanged;
import com.gh.gamecenter.eventbus.EBMiPush;
import com.gh.gamecenter.eventbus.EBPackage;
import com.gh.gamecenter.eventbus.EBShowDone;
import com.gh.gamecenter.eventbus.EBSkip;
import com.gh.gamecenter.eventbus.EBUISwitch;

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

import de.greenrobot.event.EventBus;

/**
 * 下载管理 fragment
 * 
 * @author 黄壮华
 * 
 */
public class GameDownLoadFragment extends Fragment implements View.OnClickListener {

	private View view;
	private RecyclerView downloadmanager_rv_show;
	private GameDownloadAdapter adapter;
	private LinearLayoutManager layoutManager;
	private LinearLayout reuse_nodata_skip;
	private RelativeLayout downloadmanager_rl_head;
	private TextView downloadmanager_tv_task;
	private TextView downloadmanager_tv_allstart;
	private RelativeLayout.LayoutParams rparams;

	private ArrayMap<String, Integer> locationMap;
	private ArrayMap<String, String> statusMap;
	private ArrayMap<String, String> urlMap;
	private ArrayList<String> deleteList;

	private String path;

	private DataWatcher dataWatcher = new DataWatcher() {
		@Override
		public void onDataChanged(DownloadEntity downloadEntity) {
			Integer location = locationMap.get(downloadEntity.getUrl());
			if (location != null) {
				if (!"pause".equals(statusMap.get(downloadEntity.getUrl()))) {
					int base = (adapter.getDoneList().isEmpty() ? 0 : 1 + adapter.getDoneList().size()) + 1;
					if (downloadEntity.getStatus().equals(DownloadStatus.done)) {
						// 删除下载中列表对应数据
						adapter.getDownloadingList().remove(location.intValue());
//						if (adapter.getDownloadingList().isEmpty()) {
//							adapter.notifyItemRangeRemoved(base, 2);
//						} else {
//							adapter.notifyItemRemoved(base + location);
//						}

						// 添加进已完成列表
						adapter.getDoneList().add(downloadEntity);
//						if (adapter.getDoneList().size() == 1) {
//							adapter.notifyItemRangeInserted(0, 2);
//						} else {
//							adapter.notifyItemInserted(adapter.getDoneList().size() + 1);
//						}

						urlMap.put(PackageUtils.getPackageNameByPath(getActivity(),
								downloadEntity.getPath()), downloadEntity.getUrl());
//						adapter.notifyItemChanged(base - 1);

						adapter.notifyDataSetChanged();
					} else {
						adapter.getDownloadingList().set(location, downloadEntity);
						adapter.notifyItemChanged(base + location);
					}
					if (downloadEntity.getStatus() == DownloadStatus.neterror) {
						adapter.notifyItemChanged(base - 1);
					}
				}
			} else {
				if (!deleteList.contains(downloadEntity.getUrl())) {
					DownloadStatus status = downloadEntity.getStatus();
					if (status.equals(DownloadStatus.downloading)
							|| status.equals(DownloadStatus.waiting)) {
						adapter.getDownloadingList().add(downloadEntity);
						if (adapter.getDownloadingList().size() == 1) {
							EventBus.getDefault().post(new EBDownloadChanged("download",
									View.VISIBLE, 1));
						} else {
							EventBus.getDefault().post(new EBDownloadChanged("download",
									View.VISIBLE, adapter.getDoneList().size() + adapter.getDownloadingList().size()));
						}
						locationMap.put(downloadEntity.getUrl(), adapter.getDownloadingList().size() - 1);
						int base = (adapter.getDoneList().isEmpty() ? 0 : 1 + adapter.getDoneList().size());
						if (adapter.getDownloadingList().size() == 1) {
							adapter.notifyItemRangeInserted(base, 2);
							if (reuse_nodata_skip.getVisibility() == View.VISIBLE) {
								reuse_nodata_skip.setVisibility(View.GONE);
							}
						} else {
							adapter.notifyItemInserted(base + adapter.getDownloadingList().size());
							adapter.notifyItemChanged(base);
						}
					}
				}
			}
		}
	};

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

		view = View.inflate(getActivity(), R.layout.downloadmanager, null);

		locationMap = new ArrayMap<>();
		statusMap = new ArrayMap<>();
		urlMap = new ArrayMap<>();
		deleteList = new ArrayList<>();

		downloadmanager_rl_head = (RelativeLayout) view.findViewById(R.id.downloadmanager_rl_head);
		downloadmanager_tv_task = (TextView) view.findViewById(R.id.downloadmanager_tv_task);
		downloadmanager_tv_allstart = (TextView) view.findViewById(R.id.downloadmanager_tv_allstart);
		downloadmanager_tv_allstart.setOnClickListener(this);

		rparams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);

		reuse_nodata_skip = (LinearLayout) view.findViewById(R.id.reuse_nodata_skip);
		reuse_nodata_skip.setVisibility(View.GONE);
		TextView reuse_nodata_skip_tv_hint = (TextView) view.findViewById(R.id.reuse_nodata_skip_tv_hint);
		reuse_nodata_skip_tv_hint.setText("暂无下载");
		TextView reuse_nodata_skip_tv_btn = (TextView) view.findViewById(R.id.reuse_nodata_skip_tv_btn);
		reuse_nodata_skip_tv_btn.setText("去首页看看");
		reuse_nodata_skip_tv_btn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getActivity(), MainActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				getActivity().startActivity(intent);
				new Thread(){
					@Override
					public void run() {
						try {
							sleep(300);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						EventBus.getDefault().post(new EBSkip("GameFragment", 0));
					}
				}.start();
			}
		});

		downloadmanager_rv_show = (RecyclerView) view.findViewById(R.id.downloadmanager_rv_show);
		downloadmanager_rv_show.setHasFixedSize(true);
		adapter = new GameDownloadAdapter(getActivity(), downloadmanager_rv_show, reuse_nodata_skip,
				locationMap, statusMap, deleteList);
		downloadmanager_rv_show.setAdapter(adapter);
		layoutManager = new LinearLayoutManager(getActivity());
		downloadmanager_rv_show.setLayoutManager(layoutManager);
		downloadmanager_rv_show.setOnScrollListener(new RecyclerView.OnScrollListener() {
			@Override
			public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
				super.onScrolled(recyclerView, dx, dy);

				int position = layoutManager.findFirstVisibleItemPosition();
				if (adapter.getDoneList().isEmpty()) {
					if (position >= 0) {
						downloadmanager_rl_head.setVisibility(View.VISIBLE);
						downloadmanager_tv_task.setText("下载中");
						downloadmanager_tv_allstart.setVisibility(View.VISIBLE);
					} else {
						downloadmanager_rl_head.setVisibility(View.GONE);
					}
				} else {
					if (position >= 0 && position <= adapter.getDoneList().size()) {
						downloadmanager_rl_head.setVisibility(View.VISIBLE);
						downloadmanager_tv_task.setText("已完成");
						downloadmanager_tv_allstart.setVisibility(View.GONE);
					} else if (position >= adapter.getDoneList().size() + 1) {
						downloadmanager_rl_head.setVisibility(View.VISIBLE);
						downloadmanager_tv_task.setText("下载中");
						downloadmanager_tv_allstart.setVisibility(View.VISIBLE);
					} else {
						downloadmanager_rl_head.setVisibility(View.GONE);
					}
				}

				if (adapter.getDoneList().size() != 0
						&& position == adapter.getDoneList().size()) {
					int buttom = layoutManager.findViewByPosition(position).getBottom();
					if (buttom <= downloadmanager_rl_head.getHeight()) {
						rparams.topMargin = buttom - downloadmanager_rl_head.getHeight();
						downloadmanager_rl_head.setLayoutParams(rparams);
					} else {
						rparams.topMargin = 0;
						downloadmanager_rl_head.setLayoutParams(rparams);
					}
				} else {
					rparams.topMargin = 0;
					downloadmanager_rl_head.setLayoutParams(rparams);
				}
			}
		});

		if (path != null) {
			adapter.showPluginDialog(path);
		}

		EventBus.getDefault().register(this);
	}

	@Override
	@Nullable
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		if (container != null) {
			container.removeView(view);
		}
		return view;
	}

	public void onEventMainThread(EBMiPush mipush) {
		if ("plugin_install".equals(mipush.getFrom())) {
			String path = (String) mipush.getObj();
			adapter.showPluginDialog(path);
		}
	}

	public void onEventMainThread(EBPackage busFour) {
		String packageName = busFour.getPackageName();
		String url = urlMap.get(packageName);
		if (url != null) {
			Integer location = locationMap.get(url);
			if (location != null) {
				if ("安装".equals(busFour.getType())) {
					adapter.getDoneList().remove(location.intValue());
					if (adapter.getDoneList().isEmpty() && adapter.getDownloadingList().isEmpty()) {
						EventBus.getDefault().post(new EBDownloadChanged("download", View.GONE, 0));
						locationMap.clear();
						adapter.notifyDataSetChanged();
						if (reuse_nodata_skip.getVisibility() == View.GONE) {
							reuse_nodata_skip.setVisibility(View.VISIBLE);
						}
					} else if (adapter.getDoneList().isEmpty()) {
						EventBus.getDefault().post(new EBDownloadChanged("download", View.VISIBLE,
								adapter.getDoneList().size() + adapter.getDownloadingList().size()));
						adapter.notifyItemRangeRemoved(0, 2);
					} else {
						EventBus.getDefault().post(new EBDownloadChanged("download", View.VISIBLE,
								adapter.getDoneList().size() + adapter.getDownloadingList().size()));
						adapter.notifyItemRemoved(location + 1);
					}
				}
			}
		}
	}

	public void onEventMainThread(EBUISwitch busNine) {
		if ("DownloadManagerActivity".equals(busNine.getFrom())) {
			if (busNine.getPosition() != 0) {
				deleteList.clear();
			}
		}
	}

	public void onEventMainThread(EBShowDone showDone) {
		if ("下载管理".equals(showDone.getFrom()) && downloadmanager_rv_show != null) {
			downloadmanager_rv_show.smoothScrollToPosition(showDone.getPosition());
		}
	}

	public void setPath(String path) {
		this.path = path;
	}

	@Override
	public void onResume() {
		super.onResume();
		List<DownloadEntity> list = DownloadManager.getInstance(getActivity()).getAll();
		adapter.getDownloadingList().clear();
		adapter.getDoneList().clear();
		locationMap.clear();
		statusMap.clear();
		urlMap.clear();
		DownloadEntity downloadEntity;
		for (int i = 0, size = list.size(); i < size; i++) {
			downloadEntity = list.get(i);
			statusMap.put(downloadEntity.getUrl(), downloadEntity.getStatus().name());
			if (DownloadStatus.done.equals(downloadEntity.getStatus())) {
				urlMap.put(PackageUtils.getPackageNameByPath(getActivity(),
						downloadEntity.getPath()), downloadEntity.getUrl());
				adapter.getDoneList().add(downloadEntity);
				locationMap.put(downloadEntity.getUrl(), adapter.getDoneList().size() - 1);
			} else {
				adapter.getDownloadingList().add(downloadEntity);
				locationMap.put(downloadEntity.getUrl(), adapter.getDownloadingList().size() - 1);
			}
		}

		DownloadManager.getInstance(getActivity()).addObserver(dataWatcher);

		adapter.notifyDataSetChanged();

		if (adapter.getDownloadingList().isEmpty() && adapter.getDoneList().isEmpty()) {
			reuse_nodata_skip.setVisibility(View.VISIBLE);
		} else {
			reuse_nodata_skip.setVisibility(View.GONE);
		}
	}

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

	@Override
	public void onDestroy() {
		super.onDestroy();
		EventBus.getDefault().unregister(this);
		view = null;
		downloadmanager_rv_show = null;
		reuse_nodata_skip = null;
		locationMap = null;
		statusMap = null;
		urlMap = null;
		deleteList = null;
		path = null;
		dataWatcher = null;
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.downloadmanager_tv_allstart) {
			String str = ((TextView)v).getText().toString();
			int base = (adapter.getDoneList().isEmpty() ? 0 : 1 + adapter.getDoneList().size()) + 1;
			if ("全部开始".equals(str)) {
				for (int i = 0, size = adapter.getDownloadingList().size(); i < size; i++) {
					View view = downloadmanager_rv_show.getChildAt(base + i);
					if (view != null && view instanceof CardView) {
						TextView tv = (TextView) view.findViewById(R.id.dm_item_tv_startorpause);
						if (tv.getText().toString().equals("继续")) {
							tv.performClick();
						}
					} else {
						DownloadManager.getInstance(getActivity()).put(adapter.getDownloadingList().get(i).getUrl(),
								System.currentTimeMillis());
						Message msg = Message.obtain();
						msg.what = Constants.CONTINUE_DOWNLOAD_TASK;
						msg.obj = adapter.getDownloadingList().get(i).getUrl();
						DownloadManager.getInstance(getActivity()).sendMessageDelayed(msg, 1000);
						statusMap.put(adapter.getDownloadingList().get(i).getUrl(), "downloading");
					}
				}
				downloadmanager_tv_allstart.setText("全部暂停");
				downloadmanager_tv_allstart.setTextColor(getActivity().getResources().getColor(R.color.btn_gray));
			} else {
				for (int i = 0, size = adapter.getDownloadingList().size(); i < size; i++) {
					View view = downloadmanager_rv_show.getChildAt(base + i);
					if (view != null && view instanceof CardView) {
						TextView tv = (TextView) view.findViewById(R.id.dm_item_tv_startorpause);
						if (tv.getText().toString().equals("暂停")) {
							tv.performClick();
						} else if (tv.getText().toString().equals("等待")) {
							DownloadManager.getInstance(getActivity()).pause(adapter.getDownloadingList().get(i).getUrl());
						}
					} else {
						DownloadManager.getInstance(getActivity()).put(adapter.getDownloadingList().get(i).getUrl(),
								System.currentTimeMillis());
						Message msg = Message.obtain();
						msg.what = Constants.PAUSE_DOWNLOAD_TASK;
						msg.obj = adapter.getDownloadingList().get(i).getUrl();
						DownloadManager.getInstance(getActivity()).sendMessageDelayed(msg, 1000);
					}
				}
				downloadmanager_tv_allstart.setText("全部开始");
				downloadmanager_tv_allstart.setTextColor(getActivity().getResources().getColor(R.color.theme));
			}
			adapter.notifyItemChanged(base - 1);
		}
	}
}
