package com.zxhl.cms.down

import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.app.DownloadManager
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.provider.Settings
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ProgressBar
import androidx.annotation.RequiresApi
import com.zxhl.cms.AppContext
import com.zxhl.cms.R
import com.zxhl.cms.utils.OpenFiles
import com.zxhl.cms.utils.UpdateCallback
import com.zxhl.cms.utils.Utils
import com.zxhl.cms.widget.CenterDialog


class UpdateVersionManager : UpdateVersionContract.View, View.OnClickListener {

    private val mPresenter: UpdateVersionContract.Presenter
    private val mActivity: Activity
    private var mProgress: ProgressBar? = null
    private var mDownloadDialog: Dialog? = null
    private var callBack: UpdateCallback? = null

    constructor(mActivity: Activity, callBack: UpdateCallback?) {
        this.mActivity = mActivity
        this.callBack = callBack
        mPresenter = UpdateVersionPresenter(this)
    }

    fun checkUpdate(isShowToast: Boolean) {
        mPresenter.checkVersion(isShowToast)
    }

    override fun showMandatoryUpdateDialog(title: String, desc: String) {

        var isShowLoginDialog = true
        CenterDialog.showDialogUpdateVersion(
            mActivity,
            title,
            desc,
            false,
            isShowLoginDialog,
            View.OnClickListener {
                callBack?.CheckUpate(true)
            },
            View.OnClickListener {
                showDownloadDialog()
                mPresenter.downloadApk()
            })
    }

    //非强制
    override fun showNonMandatoryUpdateDialog(title: String, desc: String) {
        var isShowLoginDialog = true
        CenterDialog.showDialogUpdateVersion(
            mActivity,
            title,
            desc,
            true,
            isShowLoginDialog,
            View.OnClickListener {
                callBack?.CheckUpate(true)
            },
            View.OnClickListener {
                showDownloadDialog()
                mPresenter.downloadApk()
            })
    }

    override fun onClick(p0: View?) {
        Log.e("MXL", "开始下载")
        showDownloadDialog()
        mPresenter.downloadApk()
    }

    override fun onNoUpdate() {
        callBack?.CheckUpate(false)
//       Utils.showToast(AppliContext.get(), "暂无更新")
    }

    override fun onDownloadError() {
        mPresenter.unsubscribe()
        Utils.showToast(AppContext.get(), "下载出错,请检查网络后重试")
        mDownloadDialog?.dismiss()
//        MobclickAgent.onEvent(AppContext.get(), UmengCountConfig.UPDATE_VERSION_ERROR)
    }

    override fun onDownloadComplete(path: String) {
        mPresenter.unsubscribe()
        mDownloadDialog?.dismiss()
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            var hasInstallPermission = isHasInstallPermissionWithO(mActivity)
//            if (!hasInstallPermission) {
//                startInstallPermissionSettingActivity(mActivity)
//            } else {
//                val dManager =
//                    AppContext.get().getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
//                var downloadFileUri = dManager.getUriForDownloadedFile(path.toLong())
//                OpenFiles.openFile(getRealFilePath(AppContext.get(), downloadFileUri))
//            }
//        } else {
//            val dManager =
//                AppContext.get().getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
//            var downloadFileUri = dManager.getUriForDownloadedFile(path.toLong())
//            OpenFiles.openFile(getRealFilePath(AppContext.get(), downloadFileUri))
//        }
        val dManager = AppContext.get().getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
        var downloadFileUri = dManager.getUriForDownloadedFile(path.toLong())
        OpenFiles.openFile(getRealFilePath(AppContext.get(), downloadFileUri))

    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    fun isHasInstallPermissionWithO(context: Context): Boolean {
        if (context == null) {
            return false;
        }
        return context.getPackageManager().canRequestPackageInstalls();
    }

    /**
     * 开启设置安装未知来源应用权限界面
     *
     * @param context
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    fun startInstallPermissionSettingActivity(context: Context) {
        if (context == null) {
            return
        }
        var intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES)
        mActivity.startActivityForResult(intent, 10001);
    }


    override fun onDownloadProgress(total: Long, current: Long) {
        Log.e("MXL", "current:" + current)
        mProgress?.progress = current.toInt()
    }

    fun getRealFilePath(context: Context, uri: Uri): String {
        if (null == uri) return ""
        val scheme = uri.getScheme()
        var data = ""
        if (scheme == null)
            data = uri.getPath().toString();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath()!!
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            var cursor = context.getContentResolver()
                .query(uri, arrayOf(MediaStore.Images.ImageColumns.DATA), null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    val index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
                    if (index > -1) {
                        data = cursor.getString(index)
                    }
                }
                cursor.close()
            }
        }
        return data
    }

    /**
     * 显示软件下载对话框
     */
    private fun showDownloadDialog() {
        // 构造软件下载对话框
        val builder = AlertDialog.Builder(mActivity)

        builder.setTitle("下载中")
        // 给下载对话框增加进度条
        val inflater = LayoutInflater.from(mActivity)
        val v = inflater.inflate(R.layout.softupdate_progress, null)
        mProgress = v.findViewById<View>(R.id.update_progress) as ProgressBar
        mProgress?.max = 100
        builder.setView(v)
        mDownloadDialog = builder.create()
        mDownloadDialog?.setCanceledOnTouchOutside(false)
        mDownloadDialog?.setCancelable(false)
        mDownloadDialog?.show()
    }

}