package com.sheep.jiuyan.samllsheep.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadTask;
import com.kfzs.duanduan.services.DownloadTaskService;
import com.kfzs.duanduan.utils.ApkUtils;
import com.kfzs.duanduan.utils.dlg.HelperUtils;
import com.kfzs.duanduan.view.DialogStorageLow;

/**
 *  @auther realicing
 * 自动更新的Service
 */

public class DownloadService extends Service{

    private DownloadTaskService mDownloadTaskService;
    @Override
    public void onCreate() {
        super.onCreate();
        Aria.download(this).register();
        mDownloadTaskService = new DownloadTaskService(this);
    }

    @Download.onPre void onPre(DownloadTask task) {
    }
    @Download.onTaskStart void taskStart(DownloadTask task) {
    }
    @Download.onTaskResume void taskResume(DownloadTask task) {
    }
    //在这里处理任务执行中的状态，如进度进度条的刷新
    @Download.onTaskRunning protected void running(DownloadTask task) {
        mDownloadTaskService.setDownloadTaskPercent(task.getPercent(), task.getCurrentProgress()/1024d/1024d,task.getFileSize()/1024d/1024d,0,task.getKey());
    }

    @Download.onTaskStop void taskStop(DownloadTask task) {
        mDownloadTaskService.setDownloadTaskStatus(task.getKey(), DownloadTaskService.STATUS_PAUSE);
    }

    @Download.onNoSupportBreakPoint void onNoSupportBreakPoint(DownloadTask task) {
    }

    @Download.onTaskCancel void taskCancel(DownloadTask task) {
        mDownloadTaskService.deleteDownloadTaskByDownloadUrl(task.getKey());
    }

    @Download.onTaskFail void taskFail(DownloadTask task) {
        mDownloadTaskService.setDownloadTaskStatus(task.getKey(), DownloadTaskService.STATUS_FAIL);
        //空间不足，弹框提示
        try{
            if (0 <= task.getFileSize() && task.getFileSize() > HelperUtils.getFreeSpaceB()) {
                DialogStorageLow.showPopupWindow(DownloadService.this);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Download.onTaskComplete void taskComplete(DownloadTask task) {
        mDownloadTaskService.setDownloadTaskFinish(task.getKey(), task.getDownloadPath());
        ApkUtils.installApk(getApplicationContext(), task.getDownloadPath());
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
