package com.kfzs.duanduan.services;

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

import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadTarget;
import com.kfzs.duanduan.KFZSApp;
import com.kfzs.duanduan.datashare.DDProviderHelper;
import com.kfzs.duanduan.datashare.provider.download.DownLoadInfo;
import com.sheep.gamegroup.model.entity.DialogEntity;
import com.sheep.gamegroup.model.entity.TaskEty;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.NetUtil;
import com.sheep.gamegroup.view.dialog.DialogAccountAbnormal;
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;

import static com.sheep.jiuyan.samllsheep.utils.ClassFileHelper.DIR;

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

public class DownloadTaskService {

    private static final String TAG = DownloadTaskService.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;

    private Context ctx;

    public DownloadTaskService(Context context) {
        this.ctx = context;
    }


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

       /* 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(ctx)
                .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(ctx, 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(TaskEty 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(String downloadUrl) {
        return DDProviderHelper
                .getInstance()
                .getDownloadTask(ctx, 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(ctx, 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(ctx, downloadUrl);
    }
    /**
     * Delete all task
     *
     * @return
     */
    public void deleteAllDownloadTask() {
        DDProviderHelper.getInstance().deleteAllDownloadTask(ctx);
    }

    /**
     * @param downloadUrl
     * @param apkPath
     */
    public void setDownloadTaskFinish(String downloadUrl, String apkPath) {
        DDProviderHelper.getInstance()
                .setDownloadTaskFinish(ctx, 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 void setDownloadTaskPercent(int percent, double downloadedSize, double totalSize, int downloadTaskId, String downloadUrl) {
        DDProviderHelper.getInstance().updateDownloadPercent(ctx, percent, downloadedSize, totalSize, downloadTaskId, downloadUrl,DownloadTaskService.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();
*/
    }

    /**
     * Set the task status
     *
     * @param downloadUrl
     * @param status
     */
    public boolean setDownloadTaskStatus(String downloadUrl, int status) {

        return DDProviderHelper.getInstance().setDownloadTaskStatus(ctx, 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(ctx);
       /* 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 void start(DownLoadInfo downLoadInfo) {

                if(!SpUtils.getDownNotice(SheepApp.mContext)
                       && NetUtil.isConnected(SheepApp.mContext)
                       && NetUtil.isMobile(SheepApp.mContext)){
                    SpUtils.saveDownNotice(SheepApp.mContext, false);

                    Jump2View.getInstance()
                            .goNoticeAct(SheepApp.mContext, new DialogEntity(null,
                                    "当前网络处于非WIFI状态，确定下载吗？",
                                    "不再提示",
                                    "确定",
                                    null,
                                    null,
                                    downLoadInfo));
                    return;
                }
        DownloadTarget task = Aria.download(KFZSApp.getInstance()).load(downLoadInfo.getMDownloadUrl());
        String filePath = DIR+ File.separator+downLoadInfo.getMPackageName()+ ClassFileHelper.FILE_SUFFIX;
        if(TextUtils.isEmpty(downLoadInfo.getMPackageName())){
            filePath = DIR+ File.separator+downLoadInfo.getMGameName()+ ClassFileHelper.FILE_SUFFIX;
        }
        task.setFilePath(filePath).start();
    }

    public void pause(DownLoadInfo downLoadInfo) {
        DownloadTarget task = Aria.download(KFZSApp.getInstance()).load(downLoadInfo.getMDownloadUrl());
        task.stop();
    }

    public void cancel(DownLoadInfo downLoadInfo) {
        DownloadTarget task = Aria.download(KFZSApp.getInstance()).load(downLoadInfo.getMDownloadUrl());
        task.stop();
        task.cancel(true);
        task.removeRecord();
    }

}
