package com.tenlionsoft.baselib.core.network.update.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.hjq.toast.ToastUtils;
import com.tenlionsoft.baselib.core.network.HttpUtils;
import com.tenlionsoft.baselib.core.network.response.DownloadResponseHandler;
import com.tenlionsoft.baselib.core.network.update.utils.ApkUtils;
import com.tenlionsoft.baselib.core.network.update.utils.Constants;
import com.tenlionsoft.baselib.core.network.update.utils.NotificationBarUtil;
import com.tenlionsoft.baselib.core.network.update.utils.NotificationHelper;
import com.tenlionsoft.baselib.core.network.update.utils.StorageUtils;

import java.io.File;

import androidx.annotation.Nullable;

/**
 * 下载服务
 */
public class DownloadService extends Service {

    private DownInfo downInfo;
    private int oldProgress = 0;
    private NotificationHelper notificationHelper;

    @Override
    public void onCreate() {
        super.onCreate();
        downInfo = new DownInfo();
        notificationHelper = new NotificationHelper(this);
    }

    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        assert intent != null;
        String urlStr = intent.getStringExtra(Constants.APK_DOWNLOAD_URL);
        downInfo.setUrl(urlStr);
        File dir = StorageUtils.getExternalCacheCustomDirectory(this);
        String apkName = System.currentTimeMillis() + ".apk";
        downInfo.setApkName(apkName);
        downInfo.setSavePath(dir.getAbsolutePath());
        downLoadFile();
        return super.onStartCommand(intent, flags, startId);
    }


    private void downLoadFile() {
        HttpUtils.getInstance().download(downInfo.getUrl(), downInfo.getSavePath(), downInfo.getApkName(), new DownloadResponseHandler() {
            @Override
            public void onFinish(File download_file) {
                //收起通知栏
                NotificationBarUtil.setNotificationBarVisibility(DownloadService.this, false);
                //安装
                ApkUtils.installAPk(DownloadService.this, download_file);
                notificationHelper.cancel();
                stopSelf();
            }

            @Override
            public void onProgress(long currentBytes, long totalBytes) {
                int progress = (int) ((currentBytes * 1.0 / totalBytes) * 100);
                if (progress != oldProgress) {
                    notificationHelper.updateProgress(progress);
                }
                oldProgress = progress;
            }

            @Override
            public void onFailure(String error_msg) {
                ToastUtils.show("App下载失败,请稍后重试");
                notificationHelper.cancel();
                stopSelf();
            }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
