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 tasks = ArrayList<Task>()
    private var isRunning = false
    private var currentTask: Task ?= null

    private val runnable = Runnable {
        while (isRunning && tasks.size > 0) {
            currentTask = tasks[0]
            currentTask!!.start()
        }
    }

    fun add(task: Task) {
        task.taskListener = object : Task.OnTaskListener {
            override fun onComplete() {
                remove(task)
            }
        }
        this.tasks.add(task)
    }

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

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

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

        return item != null
    }

    fun start() {
        if (this.isRunning) {
            Log.i(TAG, "is running")
            return
        }
        this.isRunning = true
        val t =  Thread(runnable)
        t.start()
    }

    fun stop() {
        this.tasks.clear()
        this.isRunning = false
    }

    companion object {
        val instance = TaskManager()
    }
}