package com.mayi.fastdevelop.commonpage;

import android.app.DownloadManager;
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.provider.Settings;
import android.support.annotation.Nullable;

import com.mayi.fastdevelop.base.BaseActivity;
import com.mayi.fastdevelop.bean.AppConfig;
import com.mayi.fastdevelop.constant.Key;
import com.mayi.fastdevelop.constant.RequestCode;
import com.mayi.fastdevelop.util.DownLoadUtil;
import com.mayi.fastdevelop.util.PermissionUtil;
import com.mayi.fastdevelop.util.SpUtil;
import com.mayi.fastdevelop.util.ToastUtil;
import com.mayi.fastdevelop.view.installapk.AppUpgradeManager;

/**
 * 下载安装Activity
 */
public abstract class UpdateDownLoadAPKActvity extends BaseActivity {

    private ApkInstallReceiver receiver;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.intent.action.DOWNLOAD_COMPLETE");
        filter.addAction("android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED");
        filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        receiver = new ApkInstallReceiver();
        registerReceiver(receiver, filter);
    }

    public void downLoadAPK(AppConfig appConfig) {
        AppUpgradeManager appUpgradeManager = new AppUpgradeManager(this);
        appUpgradeManager.showUpdateTipDialog(appConfig);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == RequestCode.REQUEST_CODE_APP_INSTALL) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                if (getPackageManager().canRequestPackageInstalls()) {
                    installApk();
                } else {
                    showToast("未允许应用安装，无法升级！");
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private class ApkInstallReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    //开启设置安装未知来源应用权限界面
                    if (!context.getPackageManager().canRequestPackageInstalls()) {
                        Intent intent2 = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                        startActivityForResult(intent2, RequestCode.REQUEST_CODE_APP_INSTALL);
                        ToastUtil.show(context, "请允许安装应用！");
                        return;
                    }
                }
                installApk();
            }
        }
    }

    private void installApk() {
        long id = SpUtil.get(Key.ANT_DOWNLOAD_ID, -1L);
        if (-1 != id) {
            DownloadManager dManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
            Uri downloadFileUri = dManager != null ? dManager.getUriForDownloadedFile(id) : null;
            if (downloadFileUri == null) {
                return;
            }
            PermissionUtil.installAPP(new PermissionUtil.PermissionInstallCallback() {
                @Override
                public void onSuccess() {
                    showToast("安装成功");
                    SpUtil.set(Key.ANT_DOWNLOAD_ID, -1L);
                }

                @Override
                public void onFail() {
                    showToast("安装失败");
                    SpUtil.set(Key.ANT_DOWNLOAD_ID, -1L);
                }
            }, DownLoadUtil.getRealPathFromURI(this, downloadFileUri));
        }
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(receiver);
        super.onDestroy();
    }
}
