package com.narutohuo.xindazhou.common.networkrx.download

import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream

/**
 * 下载管理器
 * 
 * 处理文件下载，支持进度监听
 * 
 * 对应 MVVMHabit 的 DownLoadManager
 */
class DownloadManager(private val client: OkHttpClient = OkHttpClient()) {
    
    /**
     * 下载文件
     * 
     * @param url 下载链接
     * @param destFile 目标文件
     * @param progressListener 进度监听器
     * @return 是否下载成功
     */
    fun download(
        url: String,
        destFile: File,
        progressListener: DownloadProgressListener? = null
    ): Boolean {
        try {
            val request = Request.Builder()
                .url(url)
                .build()
            
            val response = client.newCall(request).execute()
            
            if (!response.isSuccessful) {
                progressListener?.onError("下载失败: ${response.code}")
                return false
            }
            
            val body = response.body ?: run {
                progressListener?.onError("无响应体")
                return false
            }
            
            val totalBytes = body.contentLength()
            var downloadedBytes: Long = 0
            
            // 确保目标目录存在
            destFile.parentFile?.mkdirs()
            
            val inputStream: InputStream = body.byteStream()
            val outputStream = FileOutputStream(destFile)
            
            val buffer = ByteArray(8192)
            var bytesRead: Int
            
            while (inputStream.read(buffer).also { bytesRead = it } != -1) {
                outputStream.write(buffer, 0, bytesRead)
                downloadedBytes += bytesRead
                
                // 通知进度
                if (totalBytes > 0) {
                    val progress = (downloadedBytes * 100 / totalBytes).toInt()
                    progressListener?.onProgress(progress)
                }
            }
            
            outputStream.flush()
            outputStream.close()
            inputStream.close()
            
            progressListener?.onSuccess(destFile)
            return true
            
        } catch (e: Exception) {
            progressListener?.onError(e.message ?: "下载异常")
            e.printStackTrace()
            return false
        }
    }
    
    /**
     * 下载进度监听器
     */
    interface DownloadProgressListener {
        /**
         * 进度更新
         * 
         * @param progress 进度百分比 (0-100)
         */
        fun onProgress(progress: Int)
        
        /**
         * 下载成功
         * 
         * @param file 下载的文件
         */
        fun onSuccess(file: File)
        
        /**
         * 下载失败
         * 
         * @param errorMessage 错误信息
         */
        fun onError(errorMessage: String)
    }
    
    /**
     * 简单的下载进度监听器实现
     */
    open class SimpleDownloadListener : DownloadProgressListener {
        override fun onProgress(progress: Int) {
            // 默认实现，可重写
        }
        
        override fun onSuccess(file: File) {
            // 默认实现，可重写
        }
        
        override fun onError(errorMessage: String) {
            // 默认实现，可重写
        }
    }
}