package com.casic.br.fragment.add

import android.util.Log
import com.casic.br.R
import com.casic.br.widgets.WaterRippleView
import com.pengxh.kt.lite.base.KotlinBaseFragment
import kotlinx.android.synthetic.main.fragment_add_device_nearby.*
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

class NearbyDeviceFragment : KotlinBaseFragment() {

    private val kTag = "NearbyDeviceFragment"
    private var isRunning = true
    private lateinit var singleThreadExecutor: ExecutorService

    override fun initLayoutView(): Int = R.layout.fragment_add_device_nearby

    override fun observeRequestState() {

    }

    override fun setupTopBarLayout() {

    }

    override fun initData() {
        //只有一个核心线程，当被占用时，其他的任务需要进入队列等待
        singleThreadExecutor = Executors.newSingleThreadExecutor()
    }

    override fun initEvent() {
        waterRippleView.setOnAnimationStartListener(object :
            WaterRippleView.OnAnimationStartListener {
            override fun onStart(view: WaterRippleView?) {
                view?.start()
                //开启线程搜索设备
                Log.d(kTag, "onStart: 开始线程")
                singleThreadExecutor.execute(searchRunnable)
                isRunning = true
            }
        })
    }

    private val searchRunnable = Runnable {
        while (true) {
            try {
                if (!isRunning) {
                    Log.d(kTag, "run: 设备搜索线程休眠中...")
                    Thread.sleep(Long.MAX_VALUE)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            Log.d(kTag, "run: 设备搜索线程运行中...")
            try {
                //搜索设备
                Thread.sleep(1000)
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }
        }
    }

    override fun onPause() {
        super.onPause()
        isRunning = false
        waterRippleView.stop()
    }
}