package com.duolebo.blyrobot.tools

import android.util.Log
import com.duolebo.blyrobot.data.Task
import kotlin.collections.ArrayList

class TaskManager {
    private val TAG = "TaskManager"
    private val RUN_TASK_PERIOD = 6*60*60*1000
    val tasks = ArrayList<Task>()

    private val overTasks = ArrayList<Task>()

    var isRunning = false

    private var status = IDLE
    private var currentTask: Task ?= null
    // 处理时间
    private var updateTime = 0L

    private val runnable = Runnable {
        while (isRunning) {

            val interval = System.currentTimeMillis() - this.updateTime
            if (this.status == IDLE && interval > RUN_TASK_PERIOD) {
                this.updateTime = System.currentTimeMillis()
                this.status = RUNNING
                for (task in tasks) {
                    task.reset()

                    currentTask = task
                    currentTask!!.start()
                }
            }
            else {
                Log.i(TAG, "no task running")
            }

            Thread.sleep(3 * 1000)
        }
    }

    fun add(task: Task) {
        task.taskListener = object : Task.OnTaskListener {
            override fun onComplete(result: Boolean) {
                Log.i(TAG, "task ${task.apkInfo.name} complete with result: $result")
                overTasks.add(task)

                if (overTasks.size == tasks.size) {
                    status = IDLE
                }
            }
        }
        this.tasks.add(task)
    }

    fun remove(task: Task) {
        val item = tasks.find {
            it.apkInfo.packageName == task.apkInfo.packageName
        }

        item?.run {
            tasks.remove(this)
        }
    }

    fun isExist(task: Task): Boolean {
        val item = tasks.find {
            it.apkInfo.packageName == task.apkInfo.packageName
        }

        return item != null
    }

    fun start() {
        if (this.isRunning) {
            Log.i(TAG, "is running")
            return
        }

        if (this.tasks.size <= 0) {
            Log.i(TAG, "no tasks")
            return
        }

        this.isRunning = true
        this.status = IDLE
        val t =  Thread(runnable)
        t.start()
    }

    fun stop() {
        this.tasks.forEach {
            it.destroy()
        }

        this.overTasks.clear()
        this.isRunning = false
    }

    companion object {
        val instance = TaskManager()
        const val IDLE = 0
        const val RUNNING = 1
    }
}