package cn.thens.kdroid.sample.nature.base

import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.View
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

open class Stage(context: Context, attrs: AttributeSet? = null) : View(context, attrs) {
    private var isStarted = false
    val children = ArrayList<Sprite>()

    init {
        Observable.interval(PERIOD, TimeUnit.MILLISECONDS, Schedulers.io())
                .filter { isStarted }
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext { invalidate() }
                .subscribe()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        children.forEach { it.onDraw(canvas) }
        isStarted = true
    }

    companion object {
        const val PERIOD = 40L
        const val SPEED_FACTOR = PERIOD / 1000F
    }
}