package com.duolebo.blyrobot.tools

import android.util.Log
import com.duolebo.blyrobot.data.ImageUploadTask
import net.gotev.uploadservice.UploadService
import java.util.*

/**
 * ftp上传管理类
 * 因为ftp upload service 并不稳定，这里自己处理重新上传逻辑
 */
class FtpManager {

    companion object {
        val instance = FtpManager()
        val TAG = "RobotTaskFtpManager"
    }

    var isRunning = false
    val uploadTasks = ArrayList<ImageUploadTask>()
    private var scheduleTime: Timer? = null

    fun start() {
        Log.i(TAG, "ftp manager start...")
        if (this.isRunning)
            return
        scheduleTime?.run { cancel() }
        this.isRunning = true
        scheduleTime = Timer()
        scheduleTime!!.schedule(object : TimerTask() {
            override fun run() {
                while (isRunning) {
                    for (uploadTask in uploadTasks) {
                        if (uploadTask.needReUpload()) {
                            Log.i(TAG, "task ${uploadTask.packageName} need upload again")
                            uploadTask.start()
                        }
                    }
                    Thread.sleep(1 * 60 * 1000)
                }
            }
        }, 5 * 1000)

    }

    fun addTask(task: ImageUploadTask) {
        this.uploadTasks.add(task)
        task.uploadTaskListener = object : ImageUploadTask.OnUploadTaskListener {
            override fun onComplete() {
                uploadTasks.remove(task)
            }
        }
        task.start()
    }

    fun cancelTask(task: ImageUploadTask) {
        //如果之前的上传任务还在执行，进行取消
        if (!task.uploadId.isEmpty()) {
            UploadService.stopUpload(task.uploadId)
        }
        this.uploadTasks.remove(task)
    }

    fun stop() {
        scheduleTime?.run { cancel() }
        for (uploadTask in uploadTasks) {
            cancelTask(uploadTask)
        }
        this.isRunning = false
    }

}