package com.sheep.gamegroup.util;

import android.content.Context;
import android.os.Build;
import android.text.TextUtils;

import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.OkDownload;
import com.sheep.gamegroup.greendao.DDProviderHelper;
import com.sheep.gamegroup.greendao.download.DownLoadInfo;
import com.sheep.gamegroup.model.api.IDownload;
import com.sheep.gamegroup.model.entity.DialogEntity;
import com.sheep.gamegroup.model.entity.OrienteeringDetail;
import com.sheep.gamegroup.model.entity.TaskEty;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.ClassFileHelper;
import com.sheep.jiuyan.samllsheep.utils.SpUtils;

import java.io.File;
import java.util.List;


/**
 * The local database persistence if download task
 * The service of sql operate
 * Created by HooRang on 2017/4/11.
 */

public class DownloadUtil {

    private static final String TAG = DownloadUtil.class.getSimpleName();

    /**
     * Add a new download task , have not receive any http response
     */
    public static final int STATUS_INIT = 0X0;

    /**
     * When receive http fail response
     */
    public static final int STATUS_FAIL = 0X1;

    /**
     * The download task in processing
     */
    public static final int STATUS_ING = 0X2;

    /**
     * The download task was completed
     */
    public static final int STATUS_FINISH = 0X3;


    /**
     * The download task was paused
     */
    public static final int STATUS_PAUSE = 0X4;


    /**
     * The download task was deleted
     */
    public static final int STATUS_DELETE = 0X5;
    /**
     * The download task was deleted
     */
    public static final int STATUS_INSTALLED = 0X6;

    public DownloadUtil() {
    }

    /**
     * Query all download task details information
     *
     * @return
     */
    public List<DownLoadInfo> getAllDownloadTasks() {
        return DDProviderHelper.getInstance().getDownloadList();

       /* List<DownloadtaskBean> tasks = new ArrayList<>();
        ContentResolver contentResolver = ctx.getContentResolver();
        DownloadtaskSelection selection = new DownloadtaskSelection();
        selection.orderByCreateTime(true);

        DownloadtaskCursor query = selection.query(contentResolver);
        while (query.moveToNext()) {

            DownloadtaskBean task = new DownloadtaskBean();
            task.setCreateTime(query.getCreateTime());
            task.setDownloadedSize(query.getDownloadedSize());
            task.setTotalSize(query.getTotalSize());
            task.setDownloadTaskId(query.getDownloadTaskId());
            task.setGameName(query.getGameName());
            task.setIconUrl(query.getIconUrl());
            task.setPercent(query.getPercent());
            task.setCode(query.getCode());
            task.setDownloadUrl(query.getDownloadUrl());
            task.setApkPath(query.getApkPath());
            task.setPackageName(query.getPackageName());
            task.setVersionCode(query.getVersionCode());

            tasks.add(task);
        }
        query.close();
        Log.d(TAG, "get all tasks#" + tasks.size());
        return tasks;*/
    }


    /**
     * Query the current downloading task count
     *
     * @return
     */
    public int getDownloadingTasksCount() {
        return DDProviderHelper
                .getInstance()
                .getDownloadingTask()
                .size();
      /*  ContentResolver contentResolver = ctx.getContentResolver();
        DownloadtaskSelection selection = new DownloadtaskSelection();
        selection.status(STATUS_INIT, STATUS_ING);
        DownloadtaskCursor query = selection.query(contentResolver);
        int taskCount = query.getCount();
        query.close();
        Log.d(TAG, "get all downloading tasks#" + taskCount);
        return taskCount;*/
    }


    public boolean isDownloadExists(String downloadUrl) {
        DownLoadInfo task = DDProviderHelper
                .getInstance()
                .getDownloadTask(downloadUrl);

       /* ContentResolver contentResolver = ctx.getContentResolver();
        DownloadtaskSelection selection = new DownloadtaskSelection();
        selection.downloadUrl(downloadUrl);
        DownloadtaskCursor query = selection.query(contentResolver);
        int taskCount = query.getCount();
        query.close();*/
        return task != null;
    }


    public DownLoadInfo getDownloadTaskByUrl(IDownload taskEty) {
        DownLoadInfo downLoadInfo = getDownloadTaskByUrl(taskEty.getDownload_link());
        if (downLoadInfo == null) {
            downLoadInfo = CommonUtil.getInstance()
                    .addNewDownloadTask(taskEty.getTask_name(), taskEty.getDownload_link(), taskEty.getPackage_names(),
                            Build.VERSION.SDK_INT, taskEty.getIcon(), taskEty.getPackage_size(), taskEty.getAcceptedTaskId(), 1);
        }
        return downLoadInfo;
    }

    public DownLoadInfo getDownloadTaskByUrl(OrienteeringDetail taskEty) {
        DownLoadInfo downLoadInfo = getDownloadTaskByUrl(taskEty.getDownload_url());
        if (downLoadInfo == null) {
            downLoadInfo = CommonUtil.getInstance()
                    .addNewDownloadTask(taskEty.getName(), taskEty.getDownload_url(), taskEty.getPackage_name(),
                            Build.VERSION.SDK_INT, taskEty.getIcon(), 10 + "", taskEty.getGame_id().hashCode(), 1);
        }
        return downLoadInfo;
    }


    public DownLoadInfo getDownloadTaskByUrl(String downloadUrl) {
        return DDProviderHelper
                .getInstance()
                .getDownloadTask(downloadUrl);
        /*ContentResolver contentResolver = ctx.getContentResolver();
        DownloadtaskSelection selection = new DownloadtaskSelection();
        selection.downloadUrl(downloadUrl);

        DownloadtaskCursor query = selection.query(contentResolver);
        if (query == null || query.getCount() == 0) {
            if (query != null) {
                query.close();
            }
            return null;
        }
        DownloadtaskBean task = new DownloadtaskBean();
        if (query.moveToFirst()) {
            task.setCreateTime(query.getCreateTime());
            task.setDownloadedSize(query.getDownloadedSize());
            task.setTotalSize(query.getTotalSize());
            task.setDownloadTaskId(query.getDownloadTaskId());
            task.setGameName(query.getGameName());
            task.setIconUrl(query.getIconUrl());
            task.setPercent(query.getPercent());
            task.setCode(query.getCode());
            task.setDownloadUrl(query.getDownloadUrl());
            task.setApkPath(query.getApkPath());
            task.setPackageName(query.getPackageName());
            task.setVersionCode(query.getVersionCode());
        }
        query.close();

        return task;*/

    }

    /**
     * Add a new download task
     *
     * @param task
     */
    public boolean addDownloadTask(DownLoadInfo task) {
        if (task.getMStatus() == null) {
            task.setMStatus(0);
        }
        if (!TextUtils.isEmpty(task.getMDownloadUrl())) {
            return DDProviderHelper.getInstance().addOrUpDataDownloadTask(task);
        }
        return false;

        /*ContentResolver contentResolver = ctx.getContentResolver();
        DownloadtaskSelection where = new DownloadtaskSelection();
        where.downloadUrl(task.getDownloadUrl());
        DownloadtaskCursor cursor = where.query(contentResolver);
        if (cursor != null && cursor.getCount() == 0) {
            DownloadtaskContentValues taskValues = new DownloadtaskContentValues();
            taskValues.putCreateTime(System.currentTimeMillis());
            taskValues.putGameName(task.getGameName());
            taskValues.putIconUrl(task.getIconUrl());
            taskValues.putDownloadUrl(task.getDownloadUrl());
            taskValues.putStatus(STATUS_INIT);
            taskValues.putVersionCode(task.getVersionCode());
            taskValues.putPackageName(task.getPackageName());
            taskValues.putApkPath("");
            contentResolver.insert(taskValues.uri(), taskValues.values());
            Log.d(TAG, "insert success#" + task.getGameName());
        }

        if (null != cursor) {
            cursor.close();
        }*/
    }


    /**
     * Delete a task by download url
     *
     * @param downloadUrl
     * @return
     */
    public boolean deleteDownloadTaskByDownloadUrl(String downloadUrl) {

       /* DownloadtaskSelection where = new DownloadtaskSelection();
        where.downloadUrl(downloadUrl);
        ContentResolver contentResolver = ctx.getContentResolver();
        int delete = where.delete(contentResolver);*/
        return DDProviderHelper.getInstance().deleteDownloadTaskByUrl(downloadUrl);
    }

    /**
     * Delete all task
     *
     * @return
     */
    public void deleteAllDownloadTask() {
        DDProviderHelper.getInstance().deleteAllDownloadTask();
    }

    /**
     * @param downloadUrl
     * @param apkPath
     */
    public DownLoadInfo setDownloadTaskFinish(String downloadUrl, String apkPath) {
        return DDProviderHelper.getInstance()
                .setDownloadTaskFinish(downloadUrl, apkPath);
       /* ContentResolver resolver = ctx.getContentResolver();
        DownloadtaskSelection where = new DownloadtaskSelection();
        where.downloadUrl(downloadUrl);
        DownloadtaskCursor query = where.query(resolver);
        if (query == null) {
            return;
        }

        DownloadtaskContentValues taskValues = new DownloadtaskContentValues();
        taskValues.putStatus(STATUS_FINISH)
                .putApkPath(apkPath);

        resolver.update(taskValues.uri(), taskValues.values(), "download_url = ?", new String[]{downloadUrl});
        query.close();*/

    }

    public DownLoadInfo setDownloadTaskPercent(double downloadedSize, String averageSpeed, int downloadTaskId, String downloadUrl) {
        return DDProviderHelper.getInstance().updateDownloadPercent(downloadedSize, averageSpeed, downloadTaskId, downloadUrl, DownloadUtil.STATUS_ING);
    }

    public void setDownloadTaskPercent(int percent, double downloadedSize, double totalSize, int downloadTaskId, String downloadUrl) {
        DDProviderHelper.getInstance().updateDownloadPercent(percent, downloadedSize, totalSize, downloadTaskId, downloadUrl, DownloadUtil.STATUS_ING);



       /* ContentResolver resolver = ctx.getContentResolver();
        DownloadtaskSelection where = new DownloadtaskSelection();
        where.downloadUrl(downloadUrl);

        DownloadtaskCursor query = where.query(resolver);
        if (query == null) {
            return;
        }

        DownloadtaskContentValues taskValues = new DownloadtaskContentValues();
        taskValues.putPercent(percent);
        taskValues.putStatus(STATUS_ING);
        taskValues.putDownloadedSize(downloadedSize);

        taskValues.putTotalSize(totalSize);
        taskValues.putDownloadTaskId(downloadTaskId);
        //        if (query.getTotalSize() == null){
        //        }
        //        if(query.getDownloadTaskId() == null){
        //        }
        resolver.update(taskValues.uri(), taskValues.values(), "download_url = ?", new String[]{downloadUrl});
        query.close();
*/
    }

    /**
     * 根据下载地址，更新下载文件总大小
     *
     * @param downloadUrl
     * @param totalLength
     */
    public DownLoadInfo setDownloadTaskTotal(String downloadUrl, double totalLength) {
        return DDProviderHelper.getInstance().setDownloadTaskTotal(downloadUrl, totalLength);
    }
    /**
     * Set the task status
     *
     * @param downloadUrl
     * @param status
     */
    public DownLoadInfo setDownloadTaskStatus(String downloadUrl, int status) {

        return DDProviderHelper.getInstance().setDownloadTaskStatus(downloadUrl, status);
        /*ContentResolver resolver = ctx.getContentResolver();
        DownloadtaskSelection where = new DownloadtaskSelection();
        where.downloadUrl(downloadUrl);
        DownloadtaskCursor query = where.query(resolver);
        if (query == null || query.getCount() == 0) {
            if (query != null)
                query.close();
            return -1;
        }

        DownloadtaskContentValues taskValues = new DownloadtaskContentValues();
        taskValues.putStatus(status);

        int rowsUpdated = resolver.update(taskValues.uri(), taskValues.values(), "download_url = ?", new String[]{downloadUrl});
        query.close();
        return rowsUpdated;*/
    }


    public void restoreDownloadTaskStatus() {

        DDProviderHelper.getInstance().restoreDownloadTaskStatus();
       /* ContentResolver resolver = ctx.getContentResolver();
        DownloadtaskContentValues taskValues = new DownloadtaskContentValues();
        taskValues.putStatus(STATUS_PAUSE);
        int rowsUpdated = resolver.update(taskValues.uri(), taskValues.values(), "status = 0 or status = 2", new String[]{});

        return rowsUpdated;*/
    }


    public static DownloadTask getTask(IDownload download){
        return DownloadUtil.getTask(download.getDownload_link(),  ClassFileHelper.DIR + File.separator + download.getPackage_names() + download.getDownload_link().hashCode() + ClassFileHelper.FILE_SUFFIX);
    }


    public static DownloadTask getTask(DownLoadInfo downLoadInfo){
        return DownloadUtil.getTask(downLoadInfo.getMDownloadUrl(), downLoadInfo.getMApkPath());
    }


    public static DownloadTask getTask(String downloadUrl, String filePath){
        DownloadTask.Builder builder = new DownloadTask.Builder(downloadUrl, new File(filePath));
        // Set the minimum internal milliseconds of progress callbacks to 100ms.(default is 3000)
        builder.setMinIntervalMillisCallbackProcess(100);
        // set the priority of the task to 10, higher means less time to wait to download.(default is 0)
        builder.setPriority(10);
        // set the read buffer to 8192 bytes for the response input-stream.(default is 4096)
        builder.setReadBufferSize(8192);
        // set the flush buffer to 32768 bytes for the buffered output-stream.(default is 16384)
        builder.setFlushBufferSize(32768);
        // set this task allow using 5 connections to download data.
        builder.setConnectionCount(5);
        // build the task.
//        DownloadTask task = builder.build();
        return builder.build();
    }
    public void start(DownLoadInfo downLoadInfo) {
        if (SpUtils.getDownNotice(SheepApp.getInstance()) == 0
                && NetUtil.isConnected(SheepApp.getInstance())
                && NetUtil.isMobile(SheepApp.getInstance())) {
            SpUtils.saveDownNotice(SheepApp.getInstance(), 0);

            Jump2View.getInstance()
                    .goNoticeAct(SheepApp.getInstance(), new DialogEntity(null,
                            "当前网络处于非WIFI状态，确定下载吗？",
                            "不再提示",
                            "确定",
                            null,
                            null,
                            downLoadInfo));
            return;
        }
        if (SpUtils.getDownNotice(SheepApp.getInstance()) == 1) {//第一次不提示
            SpUtils.saveDownNotice(SheepApp.getInstance(), 0);
        }
        Jump2View.getInstance().startDownloadService(SheepApp.getInstance(), downLoadInfo);
    }

    /**
     * 删除文件并删除记录
     * @param downLoadInfo
     */
    public void delete(DownLoadInfo downLoadInfo) {
        if(downLoadInfo != null) {
            if(downLoadInfo.getMDownloadTaskId() != null) {
                OkDownload.with().downloadDispatcher().cancel(downLoadInfo.getMDownloadTaskId());
                OkDownload.with().breakpointStore().remove(downLoadInfo.getMDownloadTaskId());
            }
            if (!TextUtils.isEmpty(downLoadInfo.getMApkPath()) && new File(downLoadInfo.getMApkPath()).delete()) {
                LogUtil.println("DownloadUtil", "delete", "删除成功");
            }
        }
    }

    /**
     * 检查文件是否真的下载完成
     * @param downLoadInfo
     * @return
     */
    public boolean checkFinish(DownLoadInfo downLoadInfo) {
        if(downLoadInfo.getMApkPath() == null){
            return false;
        }
        File file = new File(downLoadInfo.getMApkPath());
        return file.exists() && downLoadInfo.getMDownloadedSize() != null && downLoadInfo.getMDownloadedSize() == (double) file.getTotalSpace();
    }
}
