package com.doverfuelingsolutions.issp.utils.download

import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.LogUtils
import com.doverfuelingsolutions.issp.api.WayneApiConfig
import com.doverfuelingsolutions.issp.utils.DFSPaths
import com.doverfuelingsolutions.issp.utils.download.entity.PackageVersion
import com.doverfuelingsolutions.issp.utils.download.entity.Versions
import com.doverfuelingsolutions.issp.utils.log.DFSLog
import com.doverfuelingsolutions.issp.utils.sp.SPKeys
import com.doverfuelingsolutions.issp.utils.sp.SPUtil
import com.thoughtworks.xstream.XStream
import com.thoughtworks.xstream.io.xml.DomDriver
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.InputStream
import java.lang.Exception
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder

object DownloadUtil {

    //检查是否有新版本
    fun checkUpdate(callback: DownloadCallback){
        if (FileUtils.isFileExists("${DFSPaths.download}/ISSPVersion.xml")) {
            FileUtils.delete("${DFSPaths.download}/ISSPVersion.xml")
        }
        val downLoadPath = "${DFSPaths.download}/ISSPVersion.xml"
        downloadFromFileName("ISSPVersion.xml",downLoadPath,object : DownloadCallback {
            override fun onDownload(isSuccess: Boolean) {
                if (isSuccess) {
                    val file = File("${DFSPaths.download}/ISSPVersion.xml")
                    if (file.exists()) {
                        val fileInputStream = FileInputStream(file)
                        val xStream = XStream(DomDriver())
                        xStream.alias("Versions", Versions :: class.java)
                        xStream.alias("PackageVersion", PackageVersion :: class.java)
                        val versions = xStream.fromXML(fileInputStream)
                        if (versions is Versions) {
                            val appVersionCode = AppUtils.getAppVersionCode()
                            var aversion: PackageVersion? = null
                            versions.PackageList.forEach { version->
                                if (version.VersionCode.toInt() > appVersionCode) {
                                    aversion = version
                                    return@forEach
                                }
                            }
                            callback.onChecked(aversion)
                        } else {
                            callback.onChecked(null)
                        }
                    } else {
                        callback.onChecked(null)
                    }
                } else {
                    callback.onChecked(null)
                }



            }
        })

    }

    //下载新版本
    fun downloadApp(appName:String,callback: DownloadCallback){
        FileUtils.deleteAllInDir(DFSPaths.dowloadApp)
        val downLoadPath = "${DFSPaths.dowloadApp}/$appName"
        downloadFromFileName(appName,downLoadPath,callback)
    }

    private fun downloadFromFileName(fileName:String,downLoadPath:String,callback: DownloadCallback){
        val urlStr = "${SPUtil.getString(SPKeys.UPDATEL_IP,WayneApiConfig.DOMAIN_DEFAULT)}:${SPUtil.getString(SPKeys.UPDATE_PORT,WayneApiConfig.PORT_ASSETS_DEFAULT)}/${URLEncoder.encode(fileName, "UTF-8")}"
        var inputStream: InputStream? = null
        val fileOutputStream = FileOutputStream(downLoadPath)
        try {
            val url = URL(urlStr)
            val httpURLConnection = url.openConnection() as HttpURLConnection
            inputStream = httpURLConnection.getInputStream()
            val contentLength = httpURLConnection.contentLength

            val dataByteArray = ByteArray(1024,{0})
            var loadLen = 0
            var len = 0
            len = inputStream.read(dataByteArray)
            while (len != -1) {
                fileOutputStream.write(dataByteArray,0,len)
                loadLen += len
                callback.onLoading(loadLen,contentLength)
                len = inputStream.read(dataByteArray)
            }

            callback.onDownload(true)
        } catch (e:Exception) {
            DFSLog.e("【app 下载】下载文件${fileName}失败",e)
            return callback.onDownload(false)
        } finally {
            inputStream?.close()
            fileOutputStream.close()
        }
    }
}