package com.gh.download.simple

import com.lg.download.*
import com.lg.ndownload.DownloadConfig
import com.lg.ndownload.DownloadDbManager
import com.lg.ndownload.DownloadQueue
import com.gh.gamecenter.common.utils.FileUtils
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

object SimpleDownloadManager {

    private val mDownloadQueue by lazy { DownloadQueue.getInstance() }
    private val mExecutor by lazy { Executors.newCachedThreadPool() }

    /**
     * 继续任务
     */
    fun resume(id: String) {
        mDownloadQueue.resume(id)
    }

    /**
     * 下载任务
     */
    fun download(config: DownloadConfig) {
        val downloadStatus = mDownloadQueue.getStatus(config.uniqueId)

        if (downloadStatus != DownloadStatus.PAUSED) {
            createNewTaskAndDownload(config)
        } else {
            try {
                resume(config.uniqueId)
            } catch (e: IllegalArgumentException) {
                createNewTaskAndDownload(config)
            }
        }
    }

    /**
     * 创建新任务并下载
     */
    private fun createNewTaskAndDownload(config: DownloadConfig) {
        ExecutorProvider.getInstance().backgroundExecutor.execute {
            mDownloadQueue.cancel(config.uniqueId)
            DownloadMessageHandler.insertDownloadToDatabase(getDownloadEntity(config))
            mDownloadQueue.submitNewTask(config)
        }
    }

    private fun getDownloadEntity(config: DownloadConfig): SimpleDownloadEntity {
        return SimpleDownloadEntity(
            id = config.uniqueId,
            url = config.url,
            fileName = config.fileName,
            dirPath = config.pathToStore,
            displayName = config.fileName,
            icon = "",
        )
    }

    /**
     * 暂停任务
     */
    fun pause(id: String) {
        mDownloadQueue.pause(id)
    }

    /**
     * 继续排队中的任务
     */
    fun resumeQueuedTask() {
        mDownloadQueue.resumeQueuedTask()
    }

    /**
     * 取消任务
     */
    fun cancel(id: String) {
        ExecutorProvider.getInstance().backgroundExecutor.execute {
            mDownloadQueue.pause(id)
            mDownloadQueue.cancel(id)

            DownloadMessageHandler.findEntity(id)?.let {
                FileUtils.deleteFile(it.dirPath + it.fileName)
                DownloadMessageHandler.deleteDownloadOfDatabase(it)
            }

            // 清除下载数据库那边的 id
            DownloadDbManager.getInstance().delete(id)
        }
    }

    fun getExecutor(): ExecutorService = mExecutor
}