package com.duolebo.blyrobot.data

import android.content.Context
import android.util.Log
import com.duolebo.blyrobot.tools.FtpManager
import com.duolebo.blyrobot.util.Config
import net.gotev.uploadservice.*
import net.gotev.uploadservice.ftp.FTPUploadRequest
import net.gotev.uploadservice.ftp.UnixPermissions
import java.io.File

/**
 * 图片上传任务
 */
class ImageUploadTask(private var context: Context) : Thread() {

    var uploadImages = ArrayList<String>()
    var uploadId: String = ""
    var reUpload = false
    var isRunning = false

    fun from(task: Task) {
        this.uploadImages.clear()
        this.uploadImages.addAll(task.uploadImages)
    }

    fun needReUpload(): Boolean {
        if (this.isRunning)
            return false

        if (!this.reUpload)
            return false

        if (isUploadRunning())
            return false

        return true
    }

    // 任务是否在上传队列中
    private fun isUploadRunning(): Boolean {
        val runningTaskIds = UploadService.getTaskList()
        if (this.uploadId in runningTaskIds)
            return true

        return false
    }

    override fun start() {
        this.isRunning = true
        super.start()
    }

    override fun run() {
        uploadImage()
    }

    private fun uploadImage() {
        Log.i(FtpManager.TAG, "upload image....")
        try {
            val uploadRequest = FTPUploadRequest(context, Config.instance.getFtpServer(), 21)
                    .setUsernameAndPassword(Config.instance.getFtpUserName(), Config.instance.getFtpPassword())
                    .setNotificationConfig(UploadNotificationConfig())
                    .setCreatedDirectoriesPermissions(UnixPermissions("777"))
                    .setSocketTimeout(15000)
                    .setConnectTimeout(15000)
                    .setDelegate(uploadImageCallback())
                    .setMaxRetries(4)

            this.uploadImages.forEach {
                val uploadFile = File(it)
                if (uploadFile.exists()) {
                    uploadRequest.addFileToUpload(it, Config.instance.getFtpRemotePath() + uploadFile.name)
                }
            }

            this.uploadId = uploadRequest.startUpload()
            Log.i(FtpManager.TAG, "upload id $uploadId")
        } catch (exc: Exception) {
            Log.e(FtpManager.TAG, exc.message, exc)
        }
    }

    private fun uploadComplete(errorCount: Int) {
        Log.i(FtpManager.TAG, "upload errorCount: $errorCount")
        this.isRunning = false
        if (errorCount > 0 && errorCount > this.uploadImages.size / 3) {
            this.reUpload = true
        } else {
            // 上传完毕直接删除问题
            this.uploadImages.forEach {
                val uploadFile = File(it)
                if (uploadFile.exists()) {
                    uploadFile.delete()
                }
            }
        }

    }

    /**
     * ftp 上传回调监听
     */
    private fun uploadImageCallback(): UploadStatusDelegate {
        val totalUpload = this.uploadImages.size
        Log.i(FtpManager.TAG, "total upload count : $totalUpload")

        return object : UploadStatusDelegate {
            override fun onCancelled(context: Context?, uploadInfo: UploadInfo?) {

            }

            override fun onProgress(context: Context?, uploadInfo: UploadInfo?) {
            }

            override fun onError(context: Context?, uploadInfo: UploadInfo?, serverResponse: ServerResponse?, exception: java.lang.Exception?) {
                val uploadSize = uploadInfo?.successfullyUploadedFiles!!.size
                Log.i(FtpManager.TAG, "onError...uploadCount: $uploadSize")
            }

            override fun onCompleted(context: Context?, uploadInfo: UploadInfo?, serverResponse: ServerResponse?) {
                val uploadSize = uploadInfo?.successfullyUploadedFiles!!.size
                Log.i(FtpManager.TAG, "onCompleted...uploadCount: $uploadSize")
                uploadComplete(totalUpload - uploadSize)
            }
        }
    }

    var uploadTaskListener: OnUploadTaskListener? = null

    /**
     * 图片上传任务状态
     */
    interface OnUploadTaskListener {
        fun onComplete()
    }
}