package com.qimai.log

import android.util.Log
import com.qimai.log.QmLog.getConfig
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.IOException
import java.util.*

object FtpUpload {


    fun upload(config: UploadConfig, uploadCallBack: UploadCallBack? = null) {
        GlobalScope.launch(Dispatchers.Main){
        uploadCallBack?.onLoading()
        val logFiles = getLogFiles(config)
        if (logFiles.isNullOrEmpty()) {
            uploadCallBack?.onError("暂无可上传日志文件")
        } else {

            try {
                for (i in logFiles.indices) {
                    val tempFile = logFiles[i]
                    if (tempFile != null) {
                        uploadFile(config.tag,tempFile)
                    }
                }
                uploadCallBack?.onSuccess()
            } catch (e: FileNotFoundException) {
                uploadCallBack?.onError(e.toString())
            }catch (e: IOException) {
                uploadCallBack?.onError(e.toString())
            }
        }
        }

    }

    suspend fun uploadFile(tag: String, file: File) = withContext(Dispatchers.IO){

    var `in`: FileInputStream? = null
    try {
        // File  logFile =
        if (!file.exists()) {
            return@withContext
        }
        `in` = FileInputStream(file)
        val isUpload = FtpUtil.uploadFile(
            "119.29.25.121", 221, "dataftp", "Data2019@#%",
            "/", tag, file.getName(), `in`
        )

    } catch (e: FileNotFoundException) {
        throw e
    } finally {
        if (`in` != null) {
            try {
                `in`.close()
            } catch (e: IOException) {
                throw e
            }
        }
    }

}

    }


    private fun getLogFiles(config: UploadConfig): Array<File?>? {
        //DBCopyUtils.copyLogToFTP();
        //int requestNum = receiverBean.getNum();
        var file: File? = null
        // final String logPath = SDCARD + "/ptcy/log";
        val logPath: String
        logPath = if (BuildConfig.DEBUG) {
            getConfig().logDebugPath
        } else {
            getConfig().logReleasePath
        }
        file = File(logPath)
        if (!file.exists()) {
            return null
        }
        //file.lastModified();
        val files: Array<File?>? = convertTimeDesc(file.listFiles())
        if (files == null || files.size == 0) {
            return null
        }
        return files
        // int maxFile = files.length;
        // int endNum = Math.min(maxFile,num);
        /*for (i in files.indices) {
            val tempFile = files[i]
            DBCopyUtils.copyLogToFTP(tempFile, config.tag)
        }*/
    }

    private fun convertTimeDesc(files: Array<File>): Array<File?>? {
        if (files == null || files.size == 0) {
            return null
        }
        val endNum = files.size
        val filesAll = arrayOfNulls<File>(20)
        val longFileTreeMap = TreeMap<Long, File>()
        for (i in files.indices) {
            val temp = files[i].lastModified()
            if (files[i].exists()) {
                longFileTreeMap[temp] = files[i]
            }
        }
        val navigableSet = longFileTreeMap.descendingKeySet()
        val iterator: Iterator<Long> = navigableSet.iterator()
        var index = 0
        while (iterator.hasNext()) {
            val file = longFileTreeMap[iterator.next()]
            //  Log.d(UploadService.TAG, "convertTimeDesc: file name= " + file!!.name)
            filesAll[index] = file
            index++
            if (index >= endNum) {
                break
            }
        }
        return filesAll
    }


    fun copyLogToFTP(file: File, tag: String?) {
        var `in`: FileInputStream? = null
        try {
            // File  logFile =
            if (!file.exists()) {
                return
            }
            `in` = FileInputStream(file)
            val isUpload = FtpUtil.uploadFile(
                "119.29.25.121", 221, "dataftp", "Data2019@#%",
                "/", tag, file.name, `in`
            )

        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } finally {
            if (`in` != null) {
                try {
                    `in`.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    }
