package com.ydl.ydlcommon.utils.receiver;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;

import com.yidianling.common.tools.LogUtil;
import com.ydl.ydlcommon.utils.ApkInstallTool;
import com.ydl.ydlcommon.utils.FileUtil2;

/**
 * 系统下载服务监听器
 */
public class DownloadReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        long completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);

        LogUtil.d("=====", "下载的IDonReceive: "+completeDownloadId);

        DownloadManager manager = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
        if(DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())){
            DownloadManager.Query query = new DownloadManager.Query();
            //在广播中取出下载任务的id
            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
            query.setFilterById(id);
            Cursor c = manager.query(query);
            if(c.moveToFirst()) {
                //获取文件下载路径
                String filename;
                if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
                    filename = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                }else {
                    filename = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
                }
                //如果文件名不为空，说明已经存在了，拿到文件名想干嘛都好
                if(filename != null){
                    LogUtil.d("=====", "下载完成的文件名为："+filename);
                    try {
                        String[] ss = filename.split("\\/");
                        String fName = ss[ss.length-1];
                        String downloadPath = FileUtil2.getLocalStorePath("download");
                        ApkInstallTool.Companion.installApk(downloadPath+"/"+fName,context);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }else if(DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(intent.getAction())){
            long[] ids = intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS);
            //点击通知栏取消下载
//            manager.remove(ids);
//            Toast.makeText(context, "已经取消下载", Toast.LENGTH_SHORT).show();

        }
    }
}
