package com.jusenr.appfircloud.home;

import android.app.DownloadManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.widget.Toast;

import com.jusenr.appfircloud.R;
import com.jusenr.toolslibrary.log.logger.Logger;
import com.jusenr.toolslibrary.utils.ToastUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;

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

/**
 * Description:
 * Copyright  : Copyright (c) 2017
 * Email      : [email protected]
 * Author     : Jusenr
 * Date       : 2017/12/11
 * Time       : 17:18
 * Project    :AppFirCloud.
 */
public class DownLoadService extends Service {
    public static final String TAG = "DownLoadService";

    public DownLoadService() {
    }

    /**
     * 广播接受者
     */
    private BroadcastReceiver mReceiver;
    /**
     * 系统下载管理器
     */
    private DownloadManager mManager;
    /**
     * 系统下载器分配的唯一下载任务id,可以通过这个id查询或者处理下载任务
     */
    private long enqueue;
    /**
     * TODO下载地址 需要自己修改,这里随便找了一个
     */
    private String apkName;
    private String downloadUrl;

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            apkName = extras.getString("name");
            downloadUrl = extras.getString("downloadurl");
            Logger.i("DownLoadService: %s", apkName + "\r\n" + downloadUrl);
//            downloadUrl = "http://pro-app-qn.fir.im/f63088ce552e398521ce5840de798c803b29dd2c.apk?attname=appcloud-v1.0.0-huawei-release.apk_V1.0.0.apk&e=1513073607&token=LOvmia8oXF4xnLh0IdH05XMYpH6ENHNpARlmPc-T:zlbPNpvxSrX779NlvRQW0kTjPr0=";
            apkName = apkName + "_" + Long.toString(System.currentTimeMillis() / 1000) + ".apk";
            Log.i(TAG, "apkName: " + apkName);
        }

        //如果路径下apk文件存在,就删除
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), apkName);
        if (file.exists()) {
            file.delete();
        }

        //创建广播对象并注册广播,用于监听下载完成后自动安装APK
        mReceiver = new DownloadCompleteReceiver();
        registerReceiver(mReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

        //下载需要写SD卡权限, targetSdkVersion>=23 需要动态申请权限
        applyPermissions();

        return Service.START_STICKY;
    }

    @Override
    public void onDestroy() {
        //服务销毁的时候 反注册广播
        if (mReceiver != null) unregisterReceiver(mReceiver);
        super.onDestroy();
    }

    // 接受下载完成后的intent
    class DownloadCompleteReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //判断是否下载完成的广播
            if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                //获取下载的文件id
                long downId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                if (downId == enqueue) {
                    //安装apk
                    installAPK(context);
                } else {
                    Toast.makeText(context, "下载失败!", Toast.LENGTH_SHORT).show();
                }
                //停止服务并关闭广播
                stopSelf();
            }
        }
    }

    private PermissionListener mPermissionListener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            if (requestCode == 101 && AndPermission.hasPermission(getApplicationContext(), Permission.STORAGE)) {
                startDownload(downloadUrl);
            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            if (requestCode == 101 && (!AndPermission.hasPermission(getApplicationContext(), Permission.STORAGE))) {
                stopSelf();
                ToastUtils.show(getApplicationContext(), getString(R.string.permission_request_denied));
                AndPermission.defaultSettingDialog(getApplicationContext());
            }
        }
    };

    /**
     * 申请权限
     */
    private void applyPermissions() {
        AndPermission.with(this)
                .callback(mPermissionListener)
                .permission(Permission.STORAGE)
                .requestCode(101)
                .start();
    }

    /**
     * 通过隐式意图调用系统安装程序安装APK
     */
    private void installAPK(Context context) {
        Log.i(TAG, "install: ");
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), apkName);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri = FileProvider.getUriForFile(context, "com.jusenr.appfircloud.android7.fileprovider", file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    /**
     * 开始下载APK
     */
    private void startDownload(String downUrl) {
        Log.i(TAG, "startDownload: ");
        //获得系统下载器
        mManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        //设置下载地址
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downUrl));
        // 设置允许使用的网络类型,这里是移动网络和wifi都可以
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        request.setAllowedOverRoaming(false);
        //设置可以被扫描到
        request.allowScanningByMediaScanner();
        //设置下载文件的类型
        request.setMimeType("application/vnd.android.package-archive");
        // 显示下载界面
        request.setVisibleInDownloadsUi(true);
        //设置下载存放的文件夹和文件名字
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, apkName);
        //设置下载时,通知栏是否显示
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        //设置标题
        request.setTitle(apkName.split("_")[0]);
        //执行下载,并返回任务唯一id
        enqueue = mManager.enqueue(request);
    }
}