package com.sobot.network.http.db;

import android.content.ContentValues;
import android.database.Cursor;

import com.sobot.network.http.model.SobotProgress;

import java.util.List;

/**
 *
 */
public class SobotDownloadManager extends SobotBaseDao<SobotProgress> {
    private static SobotDownloadManager instance;

    private SobotDownloadManager() {
        super(new SobotDBHelper());
    }

    public static SobotDownloadManager getInstance() {
        if (instance == null) {
            synchronized (SobotDownloadManager.class) {
                if (instance == null) {
                    instance = new SobotDownloadManager();
                }
            }
        }
        return instance;
    }

    @Override
    public SobotProgress parseCursorToBean(Cursor cursor) {
        return SobotProgress.parseCursorToBean(cursor);
    }

    @Override
    public ContentValues getContentValues(SobotProgress progress) {
        return SobotProgress.buildContentValues(progress);
    }

    @Override
    public String getTableName() {
        return SobotDBHelper.TABLE_FILECACHE;
    }

    @Override
    public void unInit() {
    }

    /** 获取下载任务 */
    public SobotProgress get(String tag) {
        return queryOne(SobotProgress.TAG + "=?", new String[]{tag});
    }

    /** 移除下载任务 */
    public void delete(String taskKey) {
        delete(SobotProgress.TAG + "=?", new String[]{taskKey});
    }

    /** 更新下载任务 */
    public boolean update(SobotProgress progress) {
        return update(progress, SobotProgress.TAG + "=?", new String[]{progress.tag});
    }

    /** 更新下载任务 */
    public boolean update(ContentValues contentValues, String tag) {
        return update(contentValues, SobotProgress.TAG + "=?", new String[]{tag});
    }

    /** 获取所有下载信息 */
    public List<SobotProgress> getAll() {
        return query(null, null, null, null, null, SobotProgress.DATE + " ASC", null);
    }

    /** 获取所有下载信息 */
    public List<SobotProgress> getFinished() {
        return query(null, "status=?", new String[]{SobotProgress.FINISH + ""}, null, null, SobotProgress.DATE + " ASC", null);
    }

    /** 获取所有下载信息 */
    public List<SobotProgress> getDownloading() {
        return query(null, "status not in(?) and " + SobotProgress.IS_UPLOAD + "=?", new String[]{SobotProgress.FINISH + "",SobotProgress.FALSE +""}, null, null, SobotProgress.DATE + " ASC", null);
    }

    /**
     * 更新数据的有效性，防止下载过程中退出，第二次进入的时候，由于状态没有更新导致的状态错误
     */
    public void updateDownloading2None() {
        ContentValues values = new ContentValues();
        values.put(SobotProgress.STATUS, SobotProgress.NONE);
        update(values, "status not in(?,?) and " + SobotProgress.IS_UPLOAD + "=?"
                , new String[]{SobotProgress.FINISH + "",SobotProgress.NONE+"",SobotProgress.FALSE +""});
    }

    /** 清空下载任务 */
    public boolean clear() {
        return deleteAll();
    }
}
