package com.renrenliao.model.repository

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.test.setMain

import org.junit.After

import org.junit.Before
import org.junit.Test

class RemoteDataSourceTest {

    private val mainThreadSurrogate = newSingleThreadContext("UI thread")

    @Before
    fun setUp() {
        Dispatchers.setMain(mainThreadSurrogate)

    }

    @After
    fun tearDown() {
        mainThreadSurrogate.close()
    }

    data class Stu(
        val name: String,
        val age: Int
    )

    @Test
    fun test() = runBlocking <Unit>{
//        val stu1 = Stu("c",4)
//        val stu2 = Stu("a",3)
//        val stu3 = Stu("b",1)
//        val stu4 = Stu("d",2)
//        val list = mutableListOf<Stu>()
//        list.add(stu1)
//        list.add(stu2)
//        list.add(stu3)
//        list.add(stu4)
//        val result = list.sortedBy { it.name }
//
//        println(result)
//        flowOf(1,2,3,4,5)
//            .onEach {
//                delay(100)
//            }
//            .collect {
//                println(it)
//            }
//        listOf(1, 2, 3, 4, 5).asFlow()
//            .onEach {
//                delay(100)
//            }.collect {
//                println(it)
//            }
//        val a = "123"
//        val b = "123"
//        println(a==b)
        val index = (0..2).random()
        println(index)

    }

    @Test
    fun test1() {
        runBlocking {
            val stateFlow = MutableStateFlow(1)
            val readOnlyStateFlow = stateFlow.asStateFlow() //只读flow
            //模拟外部立即订阅数据
            val launch1 = launch(Dispatchers.IO) {
                readOnlyStateFlow.collect {
                    println("模拟外部立即订阅数据 collect $it")
                }
            }
            delay(50)

            //模拟在另一个类发送数据
            val launch4 = launch(Dispatchers.IO) {
                for (i in 1..3) {
                    println("模拟在另一个类发送数据 wait emit $i")
                    stateFlow.emit(i)
                    delay(50)
                }
            }

            //模拟启动页面，在新页面订阅
            val launch2 = launch(Dispatchers.IO) {
                readOnlyStateFlow.collect{
                    println("模拟启动页面，在新页面订阅 collectAAA $it")
                }
            }

            val launch3 = launch(Dispatchers.IO) {
                readOnlyStateFlow.collect{
                    println("模拟启动页面，在新页面订阅 collectBBB $it")
                }
            }
            println("get value : ${readOnlyStateFlow.value}")
            delay(200)
            launch1.cancel()
            launch2.cancel()
            launch3.cancel()
            launch4.cancel()
        }
    }

}