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>()
    var isRunning = false
    private var status = IDLE
    private var currentTask: Task ?= null
    // 处理时间

    private val runnable = Runnable {
        while (isRunning) {

            if (this.status == IDLE) {
                for (task in tasks) {
                    task.reset()

                    currentTask = task
                    currentTask!!.start()
                }

                this.status = COMPLETE
            }
            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")
            }
        }
        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 = 0
        val t =  Thread(runnable)
        t.start()
    }

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

        this.isRunning = false
    }

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