package com.gh.download;

import android.content.Context;
import android.database.SQLException;

import com.j256.ormlite.dao.Dao;

import java.util.List;

public class DownloadDao {

	private static Dao<DownloadEntity, String> downloadDaoOpe;
	private static DBHelper helper;
	private static DownloadDao mInstance;

	private DownloadDao(Context context) throws java.sql.SQLException {
		try {
			helper = DBHelper.getInstance(context);
			downloadDaoOpe = helper.getDownloadDao();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static DownloadDao getInstance(Context context) {
		helper = DBHelper.getInstance(context);
		try {
			if (mInstance == null) {
				synchronized (DownloadDao.class) {
					if (mInstance == null) {
						mInstance = new DownloadDao(context);
					}
				}
			}
		} catch (java.sql.SQLException e) {
			e.printStackTrace();
		}
		return mInstance;
	}

	public void newOrUpdate(DownloadEntity entry) {
		try {
			if (DownloadStatus.cancel.equals(entry.getStatus())) {
				downloadDaoOpe.delete(entry);
			} else {
				downloadDaoOpe.createOrUpdate(entry);
			}
		} catch (java.sql.SQLException e) {
			e.printStackTrace();
		}
	}

	public DownloadEntity get(String url) {
		try {
			return downloadDaoOpe.queryForId(url);
		} catch (java.sql.SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public List<DownloadEntity> getAll() {
		List<DownloadEntity> list = null;
		try {
			list = downloadDaoOpe.queryForAll();
		} catch (java.sql.SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	public void delete(String url) {
		try {
			downloadDaoOpe.deleteById(url);
		} catch (java.sql.SQLException e) {
			e.printStackTrace();
		}
	}

}
