package com.duolebo.blyrobot.data

import android.content.Context
import android.util.Log
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 {

    companion object {
        const val TAG = "RobotTaskUpload"
    }

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

    private var context: Context

    constructor(context: Context) {
        this.context = context
    }

    fun from(task: Task) {
        this.packageName = task.apkInfo.packageName
        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
    }

    fun start() {
        this.isRunning = true
        Thread { uploadImage() }.start()
    }

    private fun uploadImage() {
        Log.i(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(TAG, "upload id $uploadId")
        } catch (exc: Exception) {
            Log.e(TAG, exc.message, exc)
        }
    }

    private fun uploadComplete(errorCount: Int) {
        Log.i(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()
                }
            }
        }

        uploadTaskListener?.onComplete()

    }

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

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

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

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

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

    var uploadTaskListener: OnUploadTaskListener? = null

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