package com.gh.ndownload

import com.gh.gamecenter.core.runOnUiThread
import com.lightgame.download.DownloadEntity
import com.lightgame.download.Observer
import java.util.*

/**
 *  下载进度变化通知
 */
object NDataChanger {

    private var mChanged = false
    private var mObserverVector = Vector<Observer>()

    // 当前正在下载的任务队列 (value 是 url)
    val downloadingTaskUrlSet: MutableSet<String> = Collections.synchronizedSet(hashSetOf())

    @Synchronized
    fun notifyDataChanged(entry: DownloadEntity?) {
        runOnUiThread {
            if (entry != null) {
                setChanged()
                notifyObservers(entry)
            }
        }
    }

    @Synchronized
    fun pauseDownloadingTask(url: String) {
        synchronized(downloadingTaskUrlSet) {
            downloadingTaskUrlSet.remove(url)
        }
    }

    @Synchronized
    fun addObserver(o: Observer?) {
        if (o == null) throw NullPointerException()
        if (!mObserverVector.contains(o)) {
            mObserverVector.addElement(o)
        }
    }

    @Synchronized
    fun deleteObserver(o: Observer?) {
        mObserverVector.removeElement(o)
    }

    // 修改通知观察者的顺序为 添加观察者的顺序
    fun notifyObservers(arg: Any?) {
        var arrLocal: Array<Any?>

        synchronized(this) {
            if (!hasChanged()) return
            arrLocal = mObserverVector.toTypedArray()
            clearChanged()
        }

        for (i in arrLocal.indices) (arrLocal[i] as Observer).update(arg)
    }

    @Synchronized
    fun deleteObservers() {
        mObserverVector.removeAllElements()
    }

    @Synchronized
    private fun setChanged() {
        mChanged = true
    }

    @Synchronized
    private fun clearChanged() {
        mChanged = false
    }

    @Synchronized
    fun hasChanged(): Boolean {
        return mChanged
    }

    @Synchronized
    fun countObservers(): Int {
        return mObserverVector.size
    }
}
