package com.sheep.gamegroup.greendao;

import android.content.Context;

import com.sheep.gamegroup.greendao.download.AcceptTaskRecord;
import com.sheep.gamegroup.greendao.download.AcceptTaskRecordDao;
import com.sheep.gamegroup.greendao.download.DaoMaster;
import com.sheep.gamegroup.greendao.download.DaoSession;
import com.sheep.gamegroup.greendao.download.DownLoadInfo;
import com.sheep.gamegroup.greendao.download.DownLoadInfoDao;
import com.sheep.gamegroup.greendao.download.ProcessRecord;
import com.sheep.gamegroup.greendao.download.ProcessRecordDao;
import com.sheep.gamegroup.greendao.download.ScreenShotRecord;
import com.sheep.gamegroup.greendao.download.ScreenShotRecordDao;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.jiuyan.samllsheep.service.AutoCheckService;

import java.util.List;

import rx.functions.Action1;

/**
 * 端端privoder工具
 *
 * @author kemllor
 * @date 2017/6/15   15:27
 **/

public class DDProviderHelper {

    private static DDProviderHelper mInstance;

    public static synchronized DDProviderHelper getInstance() {
        if (mInstance == null) {
            mInstance = new DDProviderHelper();
        }
        return mInstance;
    }

    private DDProviderHelper() {
    }

    /**
     * 获取下载任务列表
     *
     * @param context
     * @return
     */
    public List<DownLoadInfo> getDownloadList(Context context) {
        List<DownLoadInfo> list = getDaossion(context).getDownLoadInfoDao().queryBuilder().build().list();
        return list;
    }


    /**
     * 更新下载任务状态；
     *
     * @param context
     * @param info
     */
    public void updateDownload(Context context, DownLoadInfo info) {
        DownLoadInfoDao loadInfoDao = getDaossion(context).getDownLoadInfoDao();
        loadInfoDao.update(info);
    }

    /**
     * 添加或更新任务
     *
     * @param context
     * @param info
     */
    public boolean addOrUpDataDownloadTask(Context context, DownLoadInfo info) {
        DownLoadInfoDao infoDao = getDaossion(context).getDownLoadInfoDao();
        DownLoadInfo downLoadInfo = infoDao
                .queryBuilder()
                .where(DownLoadInfoDao.Properties.MDownloadUrl.eq(info.getMDownloadUrl()))
                .build()
                .unique();
        try{
            if (downLoadInfo == null) {
                infoDao.insert(info);
                return true;
            } else {
                info.setMId(downLoadInfo.getMId());
                infoDao.update(info);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
    /**
     * 删除所有任务；
     *
     * @param context
     */
    public void deleteAllDownloadTask(Context context) {
        DownLoadInfoDao loadInfoDao = getDaossion(context).getDownLoadInfoDao();
        loadInfoDao.deleteAll();
    }


    /**
     * 删除指定任务；
     *
     * @param context
     * @param url
     */
    public boolean deleteDownloadTaskByUrl(Context context, String url) {
        try {
            DownLoadInfoDao loadInfoDao = getDaossion(context).getDownLoadInfoDao();
            DownLoadInfo loadInfo = loadInfoDao.queryBuilder()
                    .where(DownLoadInfoDao.Properties.MDownloadUrl.eq(url))
                    .build()
                    .unique();
            loadInfoDao.delete(loadInfo);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private DaoMaster.DevOpenHelper openHelper;

    private synchronized DaoSession getDaossion(Context context) {
        if (openHelper == null) {
            openHelper = new DaoMaster.DevOpenHelper(context, "dd.db");
        }
        return new DaoMaster(openHelper.getReadableDb()).newSession();
    }

    /**
     * 获取下载中的任务；
     *
     * @param ctx
     */
    public List<DownLoadInfo> getDownloadingTask(Context ctx) {
        List<DownLoadInfo> loadInfos = getDaossion(ctx)
                .getDownLoadInfoDao()
                .queryBuilder()
                .where(DownLoadInfoDao.Properties.MStatus.eq(2))
                .build()
                .list();
        return loadInfos;
    }

    /**
     * 获取指定下载任务
     *
     * @param downloadUrl
     */
    public DownLoadInfo getDownloadTask(Context context, String downloadUrl) {
        DownLoadInfo downLoadInfo = getDaossion(context)
                .getDownLoadInfoDao()
                .queryBuilder()
                .where(DownLoadInfoDao.Properties.MDownloadUrl.eq(downloadUrl))
                .build()
                .unique();
        return downLoadInfo;
    }

    /**
     * 获取指定下载任务
     *
     * @param packName
     */
    public DownLoadInfo getDownloadTaskToPackname(Context context, String packName) {
        DownLoadInfo downLoadInfo = getDaossion(context)
                .getDownLoadInfoDao()
                .queryBuilder()
                .where(DownLoadInfoDao.Properties.MPackageName.eq(packName))
                .limit(1)
                .build()
                .unique();
        return downLoadInfo;
    }

    /**
     * 下载任务完成
     *
     * @param ctx
     * @param downloadUrl
     * @param apkPath
     */
    public void setDownloadTaskFinish(Context ctx, String downloadUrl, String apkPath) {
        DownLoadInfo downloadTask = getDownloadTask(ctx, downloadUrl);
        if (downloadTask != null) {
            downloadTask.setMApkPath(apkPath);
            downloadTask.setMStatus(3);//DownloadTaskService.STATUS_FINISH
            getDaossion(ctx).getDownLoadInfoDao().update(downloadTask);
        }
    }

    /**
     * 更新任务状态
     *
     * @param ctx
     * @param percent
     * @param downloadedSize
     * @param totalSize
     * @param downloadTaskId
     * @param downloadUrl
     */
    public void updateDownloadPercent(Context ctx, int percent, double downloadedSize, double totalSize, int downloadTaskId, String downloadUrl, int state) {
        DownLoadInfo downloadTask = getDownloadTask(ctx, downloadUrl);
        if (downloadTask != null) {
            downloadTask.setMPercent(percent);
            downloadTask.setMTotalSize(totalSize);
            downloadTask.setMDownloadedSize(downloadedSize);
            downloadTask.setMDownloadTaskId(downloadTaskId);
            downloadTask.setMStatus(state);//2下载中
            updateDownload(ctx, downloadTask);
        }
    }


    /**
     * 改变任务状态
     *
     * @param ctx
     * @param downloadUrl
     * @param status
     */
    public boolean setDownloadTaskStatus(Context ctx, String downloadUrl, int status) {
        try {
            DownLoadInfo downloadTask = getDownloadTask(ctx, downloadUrl);
            if (downloadTask != null) {
                downloadTask.setMStatus(status);
                updateDownload(ctx, downloadTask);
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * app启动  所有任务全部暂停
     *
     * @param context
     */
    public void restoreDownloadTaskStatus(Context context) {
        DownLoadInfoDao downLoadInfoDao = getDaossion(context).getDownLoadInfoDao();
        List<DownLoadInfo> list = downLoadInfoDao
                .queryBuilder()
                .whereOr(DownLoadInfoDao.Properties.MStatus.eq(0), DownLoadInfoDao.Properties.MStatus.eq(2))
                .build()
                .list();

        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                DownLoadInfo loadInfo = list.get(i);
                loadInfo.setMStatus(4);
                downLoadInfoDao.update(loadInfo);
            }
        }
    }
    /**
     * 添加或更新记录
     * 添加成功返回true
     * @param context
     * @param newInfo
     */
    public boolean addOrUpdateProcessRecord(Context context, ProcessRecord newInfo) {
        return addOrUpdateProcessRecord(context, newInfo, null);
    }
    /**
     * 添加或更新记录
     * 添加成功返回true
     * @param context
     * @param newInfo
     */
    public boolean addOrUpdateProcessRecord(Context context, ProcessRecord newInfo, Action1<ProcessRecord> action1) {
        ProcessRecordDao infoDao = getDaossion(context).getProcessRecordDao();
        ProcessRecord lastInfo = infoDao
                .queryBuilder()
                .where(ProcessRecordDao.Properties.PackageName.eq(newInfo.getPackageName()), ProcessRecordDao.Properties.UserId.eq(newInfo.getUserId()))
                .build()
                .unique();
        try{
            if(action1 != null)
                action1.call(lastInfo);
            if (lastInfo == null) {
                infoDao.insert(newInfo);
                return true;
            } else {
                newInfo.setId(lastInfo.getId());
                infoDao.update(newInfo);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
    /**
     * 根据包名获取进程运行的记录，5.0及其以下使用
     *
     * @param packageName
     */
    public ProcessRecord getProcessRecord(Context context, String packageName) {
        ProcessRecord processRecord = getDaossion(context)
                .getProcessRecordDao()
                .queryBuilder()
                .where(ProcessRecordDao.Properties.PackageName.eq(packageName))
                .build()
                .unique();
        return processRecord == null ? new ProcessRecord(): processRecord;
    }
    /**
     * 添加记录
     * 添加成功返回true
     * @param context
     * @param newInfo
     */
    public boolean addAcceptTaskRecord(Context context, AcceptTaskRecord newInfo) {
        try{
            AcceptTaskRecordDao infoDao = getDaossion(context).getAcceptTaskRecordDao();
            infoDao.insert(newInfo);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
    /**
     * 更新记录
     * 添加成功返回true
     * @param context
     * @param newInfo
     */
    public boolean updateAcceptTaskRecord(Context context, AcceptTaskRecord newInfo) {
        try{
            AcceptTaskRecordDao infoDao = getDaossion(context).getAcceptTaskRecordDao();
            infoDao.update(newInfo);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
    /**
     * 根据包名获取接受的自动审核任务的记录，5.1及其以上使用
     *
     * @param packageName
     */
    public AcceptTaskRecord getAcceptTaskRecord(Context context, String packageName) {
        return getDaossion(context)
                .getAcceptTaskRecordDao()
                .queryBuilder()
                .where(AcceptTaskRecordDao.Properties.PackageName.eq(packageName))
                .build()
                .unique();
    }
    /**
     * 删除用户的任务记录数据
     *
     * @param context
     */
    public void deleteTaskRecord(Context context) {
        if(AutoCheckService.IS_USE_THIS_SERVICE){
            ProcessRecordDao processRecordDao = getDaossion(context).getProcessRecordDao();
            processRecordDao.deleteAll();
        } else {
            AcceptTaskRecordDao acceptTaskRecordDao = getDaossion(context).getAcceptTaskRecordDao();
            acceptTaskRecordDao.deleteAll();
        }
    }
    /**
     * 添加截图记录
     * 添加成功返回true
     * @param context
     * @param newInfo
     */
    public boolean addScreenShotRecord(Context context, ScreenShotRecord newInfo) {
        try{
            ScreenShotRecordDao infoDao = getDaossion(context).getScreenShotRecordDao();
            infoDao.insert(newInfo);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
    /**
     * 获取对应包名下的截图列表
     *
     * @param ctx
     */
    public List<ScreenShotRecord> getScreenShotRecordList(Context ctx, String packageName) {
        return getDaossion(ctx)
                .getScreenShotRecordDao()
                .queryBuilder()
                .where(ScreenShotRecordDao.Properties.PackageName.eq(packageName), ScreenShotRecordDao.Properties.UserId.eq(DataUtil.getInstance().getUserId()))
                .build()
                .list();
    }
    /**
     * 是否监听到该截图
     *
     * @param ctx
     */
    public ScreenShotRecord getScreenShotRecord(Context ctx, String packageName, String imagePath) {
        return getDaossion(ctx)
                .getScreenShotRecordDao()
                .queryBuilder()
                .where(ScreenShotRecordDao.Properties.PackageName.eq(packageName), ScreenShotRecordDao.Properties.Path.eq(imagePath), ScreenShotRecordDao.Properties.UserId.eq(DataUtil.getInstance().getUserId()))
                .build()
                .unique();
    }
}
