package com.sheep.gamegroup.greendao;

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.greendao.download.SdkLoginUser;
import com.sheep.gamegroup.greendao.download.SdkLoginUserDao;
import com.sheep.gamegroup.greendao.download.SearchRecord;
import com.sheep.gamegroup.greendao.download.SearchRecordDao;
import com.sheep.gamegroup.greendao.download.Account;
import com.sheep.gamegroup.greendao.download.AccountDao;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.DownloadUtil;
import com.sheep.jiuyan.samllsheep.SheepApp;
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() {
    }

    private DaoMaster.DevOpenHelper openHelper;
    private DaoSession daoSession;

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

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


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

    /**
     * 添加或更新任务
     *
     * @param info
     */
    public boolean addOrUpDataDownloadTask(DownLoadInfo info) {
        DownLoadInfoDao infoDao = getDaossion().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;
    }

    /**
     * 删除所有任务；
     */
    public void deleteAllDownloadTask() {
        DownLoadInfoDao loadInfoDao = getDaossion().getDownLoadInfoDao();
        loadInfoDao.deleteAll();
    }


    /**
     * 删除指定任务；
     *
     * @param url
     */
    public boolean deleteDownloadTaskByUrl(String url) {
        try {
            DownLoadInfoDao loadInfoDao = getDaossion().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;
        }
    }

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

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

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

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

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

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


    /**
     * 添加文件总长度
     *
     * @param downloadUrl
     * @param totalLength
     */
    public DownLoadInfo setDownloadTaskTotal(String downloadUrl, double totalLength) {
        try {
            DownLoadInfo downloadTask = getDownloadTask(downloadUrl);
            if (downloadTask != null) {
                downloadTask.setMTotalSize(totalLength);
                updateDownload(downloadTask);
                return downloadTask;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

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

    /**
     * app启动  所有任务全部暂停
     */
    public void restoreDownloadTaskStatus() {
        DownLoadInfoDao downLoadInfoDao = getDaossion().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 newInfo
     */
    public boolean addOrUpdateProcessRecord(ProcessRecord newInfo) {
        return addOrUpdateProcessRecord(newInfo, null);
    }

    /**
     * 添加或更新记录
     * 添加成功返回true
     *
     * @param newInfo
     */
    public boolean addOrUpdateProcessRecord(ProcessRecord newInfo, Action1<ProcessRecord> action1) {
        ProcessRecordDao infoDao = getDaossion().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(String packageName) {
        ProcessRecord processRecord = getDaossion()
                .getProcessRecordDao()
                .queryBuilder()
                .where(ProcessRecordDao.Properties.PackageName.eq(packageName))
                .build()
                .unique();
        return processRecord == null ? new ProcessRecord() : processRecord;
    }

    /**
     * 添加记录
     * 添加成功返回true
     *
     * @param newInfo
     */
    public boolean addAcceptTaskRecord(AcceptTaskRecord newInfo) {
        try {
            AcceptTaskRecordDao infoDao = getDaossion().getAcceptTaskRecordDao();
            infoDao.insert(newInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 更新记录
     * 添加成功返回true
     *
     * @param newInfo
     */
    public boolean updateAcceptTaskRecord(AcceptTaskRecord newInfo) {
        try {
            AcceptTaskRecordDao infoDao = getDaossion().getAcceptTaskRecordDao();
            infoDao.update(newInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 根据包名获取接受的自动审核任务的记录，5.1及其以上使用
     *
     * @param packageName
     */
    public AcceptTaskRecord getAcceptTaskRecord(String packageName) {
        return getDaossion()
                .getAcceptTaskRecordDao()
                .queryBuilder()
                .where(AcceptTaskRecordDao.Properties.PackageName.eq(packageName))
                .build()
                .unique();
    }

    /**
     * 删除用户的任务记录数据
     */
    public void deleteTaskRecord() {
        if (AutoCheckService.IS_USE_THIS_SERVICE) {
            ProcessRecordDao processRecordDao = getDaossion().getProcessRecordDao();
            processRecordDao.deleteAll();
        } else {
            AcceptTaskRecordDao acceptTaskRecordDao = getDaossion().getAcceptTaskRecordDao();
            acceptTaskRecordDao.deleteAll();
        }
    }

    /**
     * 添加截图记录
     * 添加成功返回true
     *
     * @param newInfo
     */
    public boolean addScreenShotRecord(ScreenShotRecord newInfo) {
        try {
            ScreenShotRecordDao infoDao = getDaossion().getScreenShotRecordDao();
            infoDao.insert(newInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 获取对应包名下的截图列表
     */
    public List<ScreenShotRecord> getScreenShotRecordList(String packageName) {
        return getDaossion()
                .getScreenShotRecordDao()
                .queryBuilder()
                .where(ScreenShotRecordDao.Properties.PackageName.eq(packageName), ScreenShotRecordDao.Properties.UserId.eq(DataUtil.getInstance().getUserId()))
                .build()
                .list();
    }

    /**
     * 是否监听到该截图
     */
    public ScreenShotRecord getScreenShotRecord(String packageName, String imagePath) {
        return getDaossion()
                .getScreenShotRecordDao()
                .queryBuilder()
                .where(ScreenShotRecordDao.Properties.PackageName.eq(packageName), ScreenShotRecordDao.Properties.Path.eq(imagePath), ScreenShotRecordDao.Properties.UserId.eq(DataUtil.getInstance().getUserId()))
                .build()
                .unique();
    }

    public List<Account> getAccountList() {
        return getDaossion()
                .getAccountDao()
                .loadAll();
    }

    public Account getAccount(String aid) {
        return getDaossion()
                .getAccountDao()
                .queryBuilder()
                .where(AccountDao.Properties.Aid.eq(aid))
                .build().unique();
    }

    public void saveAccount(Account account) {
        Account acc = getAccount(account.getAid());
        if (acc == null) {
            getDaossion().getAccountDao().insert(account);
        } else {
            acc.setLoginname(account.getLoginname());
            acc.setNickname(account.getNickname());
            acc.setAvatar(account.getAvatar());
            acc.setGender(account.getGender());
            getDaossion().getAccountDao().update(acc);
        }
    }

    public void deleteAccount(Account account) {
        getDaossion().getAccountDao().delete(account);
    }

    /**
     * 获取对应服务器下所有登录过的用户列表
     */
    public List<SdkLoginUser> getSdkLoginUserList(String serviceName) {
        return getDaossion()
                .getSdkLoginUserDao()
                .queryBuilder()
                .where(SdkLoginUserDao.Properties.ServiceName.eq(serviceName))
                .build()
                .list();
    }

    /**
     * 添加或更新记录
     * 添加成功返回true
     *
     * @param newInfo
     */
    public boolean addOrUpdateSdkLoginUser(SdkLoginUser newInfo, Action1<SdkLoginUser> action1) {
        SdkLoginUserDao infoDao = getDaossion().getSdkLoginUserDao();
        SdkLoginUser lastInfo = infoDao
                .queryBuilder()
                .where(SdkLoginUserDao.Properties.ServiceName.eq(newInfo.getServiceName()), SdkLoginUserDao.Properties.Token.eq(newInfo.getToken()))
                .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;
    }

    /**
     * 删除sdkLoginUser记录
     * 删除成功返回true
     *
     * @param oldInfo
     */
    public boolean deleteSdkLoginUser(SdkLoginUser oldInfo) {
        if (oldInfo != null) {
            SdkLoginUserDao loadInfoDao = getDaossion().getSdkLoginUserDao();
            try {
                loadInfoDao.delete(oldInfo);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    SdkLoginUser loadInfo = loadInfoDao.queryBuilder()
                            .where(SdkLoginUserDao.Properties.ServiceName.eq(oldInfo.getServiceName()), SdkLoginUserDao.Properties.Token.eq(oldInfo.getToken()))
                            .build()
                            .unique();
                    loadInfoDao.delete(loadInfo);
                    return true;
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
                return false;
            }
        }
        return false;
    }

    /**
     * 添加或更新搜索记录
     * 添加成功返回true
     *
     * @param newInfo
     */
    public boolean addOrUpdateSearchRecord(SearchRecord newInfo, Action1<SearchRecord> action1) {
        SearchRecordDao infoDao = getDaossion().getSearchRecordDao();
        SearchRecord lastInfo = infoDao
                .queryBuilder()
                .where(SearchRecordDao.Properties.Input.eq(newInfo.getInput()))
                .build()
                .unique();
        try {
            if (action1 != null)
                action1.call(lastInfo);
            if (lastInfo == null) {
                newInfo.setFirst_time(newInfo.getLast_time());
                infoDao.insert(newInfo);
                return true;
            } else {
                newInfo.setId(lastInfo.getId());
                newInfo.setFirst_time(lastInfo.getLast_time());
                newInfo.setCount(lastInfo.getCount() + newInfo.getCount());
                infoDao.update(newInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 获取搜索历史（根据搜索次数来排序）
     */
    public List<SearchRecord> getSearchRecordList(int limit) {
        return getDaossion()
                .getSearchRecordDao()
                .queryBuilder()
                .limit(limit)
                .orderDesc(SearchRecordDao.Properties.Count)
                .build()
                .list();
    }

    /**
     * 删除搜索记录
     * 删除成功返回true
     *
     * @param oldInfo
     */
    public boolean deleteSearchRecord(SearchRecord oldInfo) {
        if (oldInfo != null) {
            SearchRecordDao loadInfoDao = getDaossion().getSearchRecordDao();
            try {
                loadInfoDao.delete(oldInfo);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    SearchRecord loadInfo = loadInfoDao.queryBuilder()
                            .where(SearchRecordDao.Properties.Input.eq(oldInfo.getInput()))
                            .build()
                            .unique();
                    if (loadInfo != null)
                        loadInfoDao.delete(loadInfo);
                    return true;
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
                return false;
            }
        }
        return false;
    }
}
