package com.gh.download;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;

import com.gh.common.constant.Constants;
import com.gh.common.util.Utils;
import com.gh.gamecenter.eventbus.EBDownloadStatus;

import java.util.Map.Entry;

import de.greenrobot.event.EventBus;

public class DownloadService extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Utils.log(DownloadService.class.getSimpleName(), "onStartCommand");
		if (intent != null && intent.getExtras() != null) {
			DownloadStatus status = DownloadStatus.valueOf(intent
					.getStringExtra(Constants.KEY_DOWNLOAD_ACTION));
			DownloadEntity entry = (DownloadEntity) intent
					.getSerializableExtra(Constants.KEY_DOWNLOAD_ENTRY);
			switch (status) {
				case add:
					addDownload(entry);
					break;
				case pause:
				case timeout:
				case neterror:
					pauseDownload(entry);
					break;
				case resume:
					resumeDownload(entry);
					break;
				case cancel:
					cancelDownload(entry);
					break;
				default:
					break;
			}
		}
		return super.onStartCommand(intent, flags, startId);
	}

	private synchronized void addDownload(DownloadEntity entry) {
		DownloadEntity downloadEntity = DownloadDao.getInstance(this).get(
				entry.getUrl());
		// 数据库下载历史中有这个任务的下载记录
		if (downloadEntity != null) {
			entry = downloadEntity;
		}

		if (DataChanger.getInstance().getDownloadingTasks().size() >= Constants.MAX_DOWNLOADING_SIZE) {
			// 1.改任务队列的状态
			entry.setStatus(DownloadStatus.waiting);
			DataChanger.getInstance().getDownloadEntries().put(entry.getUrl(), entry);
			// 2.改数据库状态
			DownloadDao.getInstance(this).newOrUpdate(entry);
			// 3.通知更新
			DataChanger.getInstance().notifyDataChanged(entry);
		} else {
			startDownload(entry);
		}
		Utils.log(DownloadService.class.getSimpleName(), "addDownload==>" + entry);
		EventBus.getDefault().post(new EBDownloadStatus("download"));
	}

	private synchronized void startDownload(DownloadEntity entry) {
		// 1.改任务队列的状态
		entry.setStatus(DownloadStatus.downloading);
		DataChanger.getInstance().getDownloadEntries().put(entry.getUrl(), entry);
		DownloadTask task = new DownloadTask(handler, entry, this);
		task.start();
		DataChanger.getInstance().getDownloadingTasks().put(entry.getUrl(), task);
		// 2.改数据库状态
		DownloadDao.getInstance(this).newOrUpdate(entry);
		// 3.通知更新
		DataChanger.getInstance().notifyDataChanged(entry);

		Utils.log(DownloadService.class.getSimpleName(), "startDownload==>" + entry);
	}

	private synchronized void resumeDownload(DownloadEntity entry) {
		addDownload(entry);
		Utils.log(DownloadService.class.getSimpleName(), "resumeDownload==>" + entry);
	}

	private synchronized void pauseDownload(DownloadEntity entry) {
		if (entry != null) {
			DownloadTask task = DataChanger.getInstance().getDownloadingTasks()
					.get(entry.getUrl());
			if (task != null) {
				// 1.改任务队列的状态
				entry.setStatus(DownloadStatus.pause);
			}
			DataChanger.getInstance().pauseDownloadingTasks(entry.getUrl());
			entry.setStatus(DownloadStatus.pause);
			// 2.改数据库状态
			DownloadDao.getInstance(this).newOrUpdate(entry);
			// 3.通知更新
			DataChanger.getInstance().notifyDataChanged(entry);
		}
		Utils.log(DownloadService.class.getSimpleName(), "pauseDownload==>" + entry);
	}

	private synchronized void cancelDownload(DownloadEntity downloadEntity) {
		DownloadTask task = DataChanger.getInstance().getDownloadingTasks()
				.get(downloadEntity.getUrl());
		if (task != null) {
			task.cancel();
			// 改任务队列的状态
			DataChanger.getInstance().getDownloadingTasks().remove(downloadEntity.getUrl());
			DataChanger.getInstance().notifyDataChanged(downloadEntity);
		}
		if (downloadEntity != null) {
			DataChanger.getInstance().getDownloadEntries().remove(downloadEntity.getUrl());
			DataChanger.getInstance().notifyDataChanged(downloadEntity);
		}
		Utils.log(DownloadService.class.getSimpleName(), "cancelDownload==>" + downloadEntity);
		EBDownloadStatus status = new EBDownloadStatus("delete", downloadEntity.getName(),
				downloadEntity.getPlatform(), downloadEntity.getUrl());
		status.setPluggable(downloadEntity.isPluggable());
		EventBus.getDefault().post(status);
	}

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			DownloadEntity entry = (DownloadEntity) msg.obj;
			DataChanger.getInstance().notifyDataChanged(entry);

			if (msg.what == 1 && msg.obj != null) {
				switch (entry.getStatus()) {
				case downloading:
					break;
				case done:
					removeAndCheckNext(entry);
					break;
				case pause:
//					pauseDownload(entry);
					removeAndCheckNext(entry);
					break;
				case cancel:
					removeAndCheckNext(entry);
					break;
				default:
					break;
				}
			}
		}
	};

	private synchronized void removeAndCheckNext(DownloadEntity downloadEntity) {
		DataChanger.getInstance().getDownloadingTasks().remove(downloadEntity.getUrl());
		DataChanger.getInstance().getDownloadEntries().remove(downloadEntity.getUrl());
		for (Entry<String, DownloadEntity> entry : DataChanger.getInstance()
				.getDownloadEntries().entrySet()) {
			if (entry.getValue().getStatus() == DownloadStatus.waiting) {
				startDownload(entry.getValue());
				return;
			}
		}
		Utils.log(DownloadService.class.getSimpleName(), "removeAndCheckNext==>" + downloadEntity);
	}

}
